Mail Send using Queue in Laravel 8 Example

In this turorial we wil see how we can send email using queue in laravel 8. Sometimes sending email to multiple users may take time. so to overcome this we can push emails in queue. Queue will send email in background without delaying the response time.

Step - 1 : Create new laravel application

composer create-project --prefer-dist laravel/laravel guzzle_request

Step - 2 : Database Configuration

configure dstabase settings in .env file according to your local/server setup for following .env variables. As we are going to use database queue driver for queueing the mail.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydatabase
DB_USERNAME=root
DB_PASSWORD=secret

Step - 3 : Generate Mail class

php artisan make:mail QueueEmail

After executing the above command, we will have QueueEmail.php file under app\Mail directory.Edit that file as follows.

QueueEmail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class QueueEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.testQueueMail');
    }
}

Step - 4 : Create mail template

create email file under resources/emails/testQueueMail as follows.

<html>
<head>
    <title>Laravel 8 Mail Send using Queue Example</title>
</head>
<body>
<p> This is test email and sent using queue.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  
</body>
</html>

Step - 5 : Configure email in .env file

set values of following variables of .env file according to your email id.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAM[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

Step - 6 : Configure Queue

set queue driver as database

QUEUE_CONNECTION=database

generate migration and migrate databse

php artisan queue:table

php artisan migrate

Step - 6 : Create Queue Job

generate job class using command

php artisan make:job QueueJob

After executing above command You will have new File named QueueJob.php under app\Jobs directory.

QueueJob.php

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Mail\QueueEmail;
use Mail;

class QueueJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $email_list;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($email_list)
    {
        $this->email_list = $email_list;
    }

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

Step - 7 : Create Route

Now everything else is all set. now we just need to push the task in queue and disptch the job.

web.php

Route::get('queue-email', function(){
  
    $email_list['email'] = '[email protected]';
  
    dispatch(new \App\Jobs\QueueJob($email_list));
  
    dd('Send Email Successfully');
});

Step - 8 : Run the application

run this in terminal

php artisan server

run this in browser

localhost:8000/queue-email

you can watch your queue process using below laravel queue command. You can see output while job is being processed.

php artisan queue:listen

 

Tags: