DEV Community

Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

Send Email using Queue in Laravel 5.8

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.*"
Enter fullscreen mode Exit fullscreen mode

Create Email in Laravel

php artisan make:mail SendEmailDemo
Enter fullscreen mode Exit fullscreen mode

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

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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

<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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Create Queue Job

php artisan make:job SendEmailJob
Enter fullscreen mode Exit fullscreen mode

Run the following above command, we'r create SendEmailJob.php file in App\Jobs directory, your need add App\Mail\SendEmailDemo.phpto SendEmailJob.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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Create File Controller

php artisan make:controller EmailController --resource
Enter fullscreen mode Exit fullscreen mode

Okay next step, open EmailController.php file in App\Http\Controller directory, pass the following code it

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');
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

Create file View Blade
We'r will create email.blade.php file in App/resources/Views directory.

//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
Enter fullscreen mode Exit fullscreen mode

Configuration Route
Open web.php file in Routes/web.php directory

Route::prefix('email')->group(function () {
    Route::get('/','EmailController@index')->name('email.index');
    Route::post('/email','EmailController@store')->name('email.store');
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Open browser http://localhost:8000/email
Send Email using queue in Laravel 5.8 - hoanguyenit.com

Send Email using queue in Laravel 5.8 - hoanguyenit.com

Send Email using queue in Laravel 5.8 - hoanguyenit.com

Post:Send Email using Queue in Laravel 5.8 -> See more posts

Top comments (0)