Laravel 8 — How to use Queue to Send Email

Welcome back to CodePortal.. In this article, we’ll learn how to use Laravel’s Queue feature to Send Email to avoid delay.

In your experience with Laravel to Send Email, you must have felt some delay in functionality where you need to send emails to user like login alert, signup mail, forgot password mail. This delay happens as your code has to wait for email process to be completed. To avoid this, you can use Queue which is Laravel’s inbuilt feature which will insert process into Queue. This will make your application lot faster than usual.

So, without any further delay, let’s integrate Queue into Send Email functionality. I’ll guide you through a simple demo on how to configure queue.

1. Install fresh copy of Laravel 8

First of all we need fresh copy of Laravel 8. Run following command to get it:

composer create-project ––prefer-dist laravel/laravel laravel-email-queue

2. Create Mail Class

Once you have setup Laravel project, go into the root directory and run following command to create Mail class:

php artisan make:mail EmailQueueTest

With this command, you’ll have new folder Mail inside app directory with EmailQueueTest.php file. Just paste following sample code into that file and save it

app/Mail/EmailQueueTest.php

<?php

  

namespace App\Mail;

  

use Illuminate\Bus\Queueable;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Mail\Mailable;

use Illuminate\Queue\SerializesModels;

  

class EmailQueueTest 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.queue-test');

    }

}

3. Prepare Email Template

Now, let’s create email template file inside view directory.

Create folder “emails” inside resources/views and then create queue-test.blade.php file inside that. Once you do that, just paste following sample template into this file:

resources/views/emails/queue-test.blade.php

<!DOCTYPE html>

<html>

<head>

    <title>Using Queue to Send Email -- CodePortal</title>

</head>

<body>

   <p>This is test mail</p>

</body>

</html>

It seems basic but we’ll use this just for testing purpose so it will work 🙂

4. Configurations

Configuring SMTP details are the main part. You can’t send email without configuring SMTP credentials inside your .env file

.env

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=codeportal@gmail.com
MAIL_PASSWORD=codeportal123
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=codeportal@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

5. Queue Configurations

Now, its time to start implementing Queue. We’ll be defining some more values to .env file, creating migrations for Queue, creating Queue Job.

i. We’ll set database drivers in .env

QUEUE_CONNECTION=database

ii. Create and Run queue migrations

php artisan queue:table

php artisan migrate

iii. Create Queue Job

After migration, execute following command to create Queue Job:

php artisan make:job SendEmailJob

Above command will create new directory Jobs inside app. If you open Jobs directory, you can see SendEmailJob.php file. Just paste following code inside that file:

<?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\EmailQueueTest;

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 EmailQueueTest();

        Mail::to($this->details['email'])->send($email);

    }

}

so, now that we’ve configured Queue Job, next step is to use this job and test it out.

6. Integrate Queue and Test

routes/web.php

Route::get('email-test', function(){
    $details['email'] = 'harshdoshi999@gmail.com';


    dispatch(new App\Jobs\SendEmailJob($details));

    dd('sent');
});

Finally, we’ve configured our route to test queue. Final and Last step is to clear configurations and start Laravel server

php artisan config:clear

php artisan serve

Open another terminal and run following command to listen your queue

php artisan queue:listen

Now run your project and bellow link:

http://localhost:8000/email-test

Phew.. after lots of commands and configurations, we’ve finally implemented Queue with Send Email functionality in Laravel 8!!

Leave a Reply

Your email address will not be published.

3 × 1 =