Send Email using Queue in Laravel 5.8
Tags: laravel
Published: 2019-09-27 09:14:41

Here, I'm going shared a simple example to Send email using Queue in Laravel 5.8. 
The first, we'r need set up laravel 5.8 verison
**Setup Laravel 5.8 version**
```
composer create-project --prefer-dist laravel/laravel blog "5.8.*"
```
**Create Email in Laravel**
```
php artisan make:mail SendEmailDemo
```

We run the following below command create SendEmailDemo file in App\Mail directory, we need open it and copy the following below code pass it
```php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendEmailDemo extends Mailable
{
    use Queueable, SerializesModels;
    protected $details;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('testemail')->with("details",$this->details);
    }
}
```
Okay, your see function build() it return view('testemail'), so let's your need create testmail.blade.php file in App/resources/Views directory, we need configuration template send email 
```html
<div style="border:1px solid red;border-radius:5px;padding:10px;box-size:border-box;">
	<h1>{{$details['title']}} - hoanguyenit.com<h1>
	<span style="font-size:13px">{{$details['email']}}</span>
	<p style="font-size:15px;line-height:25px;">
		{{$details['body']}}
	</p>
</div>
```
**Configuration Queue**
Next step, open .env file configuration send email 
```
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=email@gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
QUEUE_CONNECTION=database
```
Ok, when your config success! your need run command two the following below, your see table Jobs in database, it save queue list, when your send email
```
php artisan queue:table
php artisan migrate
```
**Create Queue Job**
```
php artisan make:job SendEmailJob
```
Run the following above command, we'r create SendEmailJob.php file in App\Jobs directory, your need add **App\Mail\SendEmailDemo.php**to **SendEmailJob.php**
```php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Mail\SendEmailDemo;
use Mail;
class SendEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $details;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $email = new SendEmailDemo($this->details);
        Mail::to($this->details['email'])->send($email);
    }
}
```

**Create File Controller**
```
php artisan make:controller EmailController --resource
```
Okay next step, open EmailController.php file in **App\Http\Controller** directory, pass the following code it
```php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Jobs\SendEmailJob;
class EmailController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return View('email');
    }
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'title' => 'required|max:255',
            'body' => 'required',
        ]);
        if($validatedData){
            $details=[
                "email"=>"thanhhoacth2013@gmail.com",
                "title"=>$request->title,
                "body"=>$request->body
            ];
            dispatch(new SendEmailJob($details));
            return redirect()->route('email.index');
        }
     
    }
}
```
**Create file View Blade**
We'r will create **email.blade.php** file in **App/resources/Views** directory. 
```html
//email.blade.php 
@extends('layouts.app')
@section('content')

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-4">
        <h2>Send Email using Laravel 5.8</h2>
        @if ($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
            <form action="{{route('email.store')}}" method="post">
            @csrf
                <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" name="title" placeholder="Title" class="form-control"/>
                </div>
                <div class="form-group">
                    <label for="body">Body</label>
                    <input type="text" name="body" placeholder="Body" class="form-control"/>
                </div>
                <div class="form-group">
                    <input type="submit" name="submit" value="Send Email" class="btn btn-success"/>
                </div>
            </form>
        </div>
        <div class="cold-md-8">
            <div id="calendar"></div>
        </div>
    </div>
</div>
@endsection
```
**Configuration Route**
Open web.php file in Routes/web.php directory
```php
Route::prefix('email')->group(function () {
    Route::get('/','EmailController@index')->name('email.index');
    Route::post('/email','EmailController@store')->name('email.store');
});
```
**Test Send Email using Queue**
we need open command two, run the following below command 
```
command 1: php artisan queue:listen
command 2: php artisan serve
```
Open browser http://localhost:8000/email 
![Send Email using queue in Laravel 5.8 - hoanguyenit.com](https://thepracticaldev.s3.amazonaws.com/i/5gzpzs5j2xrpg9bph23b.jpg)

![Send Email using queue in Laravel 5.8 - hoanguyenit.com](https://thepracticaldev.s3.amazonaws.com/i/10vy5nwluo8b025qx9mk.jpg)

![Send Email using queue in Laravel 5.8 - hoanguyenit.com](https://thepracticaldev.s3.amazonaws.com/i/v324js5nhvptogupgocl.jpg)

Post:[Send Email using Queue in Laravel 5.8](https://hoanguyenit.com/send-email-using-queue-in-laravel-58.html) -> [See more posts](https://hoanguyenit.com)