How To Send Mail By Using Queue In Laravel 9 ?

Today now in this tutorial i will show you laravel 9 send email by using queue. Here i will explain this step by step how to send mail by using queue in laravel 9. Here i will help you to give an example of laravel 9 send mail by using queue. So I would like to show you an example of laravel 9 send mail in queue. We just need to some steps to do laravel 9 send an email with a queue.

Sometimes, we are see some processes take time to load like email send, payment gateway, etc. When we send an email for the verification or send an invoice then it can loads time to send mail because it is services. If we don’t want to wait for the user to send an email or other process on loading server-side process then we can use a queue. Because it’s a very fast and visitors will be happy to see loading time.

Now in this example, i will create one mail class and then create a job class. We can send the test mail by using a queue. Just need to follow the below step and make it done this example:

Step 1: Install Laravel 9

This is first step but this step is optional; however, if you do not have then need to created the laravel app. then you may go ahead and then execute the below command:

composer create-project laravel/laravel example-app
Step 2: Create Mail Class with Configuration

Here i am going from the scratch and in first step, i will create the email for testing by using Laravel Mail facade. So let’s simple run the bellow command.

php artisan make:mail SendEmailTest

Now i will create a new folder “Mail” in app directory also with SendEmailTest.php file. So let’s the simply copy the bellow code and past on that file.

app/Mail/SendEmailTest.php

<?php
  
namespace App\Mail;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
  
class SendEmailTest 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.test');
    }
}

Ok, now we need to create the email view by using blade file. So i will create the simple view file and then copy the bellow code om following path.

resources/views/emails/test.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to send mail using queue in Laravel 9? - Codingspoint.com</title>
</head>
<body>
   
<center>
<h2 style="padding: 23px;background: #b3deb8a1;border-bottom: 6px green solid;">
    <a href="https://Codingspoint.com">Visit Our Website : Codingspoint.com</a>
</h2>
</center>
  
<p>Hi, Sir</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor 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>
  
<strong>Thank you Sir. :)</strong>
  
</body>
</html>

after the configuration of view file, we need to setup for email send, So let’ set the configuration in .env file:

.env

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Step 3: Queue Configuration

Now in this step, i will make the configuration on queue driver so at first of all, i will set queue driver “database”. We can set as we want also we will define the driver as Redis too. So here define the database driver on “.env” file:

.env

QUEUE_CONNECTION=database

After that i have to generate the migration and then create tables for queue. So let’s run the bellow command for queue database tables:

Generate Migration:

php artisan queue:table

Run Migration:

php artisan migrate
Step 4: Create Queue Job

So here i will create the queue job by using the following command, this command will be create queue job file also with Queueable. So let’s run the bellow command:

php artisan make:job SendEmailJob

Now we have SendEmailJob.php file in the “Jobs” directory. So let’s see that file and then put the bellow code on that file.

app/Jobs/SendEmailJob.php

<?php
  
namespace App\Jobs;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Mail\SendEmailTest;
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 SendEmailTest();
        Mail::to($this->details['email'])->send($email);
    }
}
Step 5: Test Queue Job

Now in this time to use and test the created queue job, so let’s do this simple create route with the following code for testing created queue.

routes/web.php

Route::get('email-test', function(){
  
    $details['email'] = 'your_email@gmail.com';
  
    dispatch(new App\Jobs\SendEmailJob($details));
  
    dd('done');
});

Next, we must have to run the following command to see the queue process, we must have to keep start this command:

php artisan queue:work

Read Also: How To Implement Laravel 9 form validation ?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →