How to Send Email using Queue in Laravel 11?

29-Mar-2024

.

Admin

How to Send Email using Queue in Laravel 11?

Hello Dev,

In this guide, I'll illustrate how to utilize a queue to send emails efficiently within a Laravel 11 application.

Oftentimes, certain tasks such as email dispatching or handling payment gateways may introduce delays in loading processes. Sending emails for verification or invoicing, for instance, can be time-consuming due to the nature of the service. To mitigate this and ensure a smoother user experience without prolonged wait times, leveraging a queue system is highly advantageous. Queues offer rapid processing, thereby enhancing user satisfaction by minimizing loading times.

Here's a step-by-step walkthrough to implement this functionality:

Step for How to Send Email Using Queue in Laravel 11?


Step 1: Install Laravel 11

Step 2: Queue Configuration

Step 3: Make Mail Configuration

Step 4: Create Mail Class

Step 5: Create Controller

Step 6: Create Routes

Step 7: Create Blade View

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Queue Configuration

Now, in the next step, we will make configurations on the queue driver. First of all, we will set the queue driver to "database". You can set it as you want. Additionally, we will define the driver as Redis too. So, define the database driver in the .env file:

.env

QUEUE_CONNECTION=database

After that, we need to generate migration and create tables for the queue. So let's run the below command for queue database tables:

Generate Migration:

php artisan make:queue-table

Run Migration:

php artisan migrate

Step 3: Make Mail Configuration

In the second step, you have to add the mail configuration. Set the mail driver as "gmail", the mail host, mail port, mail username, and mail password. Laravel 11 will use these sender details for emails. You can simply add them as follows:

.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 4: Create Mail Class

In this step, we will create a mail class called `DemoMail` for sending emails. Here, we will write code for which view will be called and the object of the user. So let's run the below command.

php artisan make:mail DemoMail

Now, let's update the code in the `DemoMail.php` file as follows:

app/Mail/DemoMail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Mail\Mailable;

use Illuminate\Mail\Mailables\Content;

use Illuminate\Mail\Mailables\Envelope;

use Illuminate\Queue\SerializesModels;

class DemoMail extends Mailable

{

use Queueable, SerializesModels;

/**

* Create a new message instance.

*/

public function __construct(public $mailData)

{

//

}

/**

* Get the message envelope.

*/

public function envelope(): Envelope

{

return new Envelope(

subject: 'Demo Mail',

);

}

/**

* Get the message content definition.

*/

public function content(): Content

{

return new Content(

view: 'emails.demoMail'

);

}

/**

* Get the attachments for the message.

*

* @return array

*/

public function attachments(): array

{

return [];

}

}

Step 5: Create Controller

In this step, we will create a `MailController` with an `index()` method where we will write code to send an email using queue to a given email address. we will use queue() to send mail in queue. So first, let's create the controller by executing the following command and update the code in it:

php artisan make:controller MailController

Now, update the code in the MailController file.

app/Http/Controllers/MailController.php

<?PHP

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Mail;

use App\Mail\DemoMail;

class MailController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$mailData = [

'title' => 'Mail from NiceSnippets.com',

'body' => 'This is for testing email using smtp.'

];

Mail::to('your_email@gmail.com')->queue(new DemoMail($mailData));

dd("Email is sent successfully.");

}

}

Step 6: Create Routes

In this step, we need to create routes for a list of sending emails. So, open your "routes/web.php" file and add the following route.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\MailController;

Route::get('send-mail', [MailController::class, 'index']);

Step 7: Create Blade View

In this step, we will create a blade view file and write the email that we want to send. Now, we will just write some dummy text. Create the following files in the "emails" folder.

resources/views/emails/demoMail.blade.php

<!DOCTYPE html>

<html>

<head>

<title>NiceSnippets.com.com</title>

</head>

<body>

<h1>{{ $mailData['title'] }}</h1>

<p>{{ $mailData['body'] }}</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>

<p>Thank you</p>

</body>

</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

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

php artisan queue:work

You will see layout as like bellow if queue is works:

laravel-11-send-mail-queue

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/send-mail

Output:

laravel-11-send-email

Keep Laravel Queue System Running on Server:

As we know we must need to keep running "php artisan work" command on the terminal because then and then queue will work. so in server, you must have to keep running using Supervisor. A supervisor is a process monitor for the Linux operating system, and will automatically restart your queue:work processes if they fail.

So let's install Supervisor using bellow command:

Install Supervisor:

sudo apt-get install supervisor

Next, we need to configuration file on supervisor as below following path, you can set project path, user and output file location as well:

/etc/supervisor/conf.d/laravel-worker.conf

[program:laravel-worker]

process_name=%(program_name)s_%(process_num)02d

command=php /home/forge/app.com/artisan queue:work sqs --sleep=3 --tries=3 --max-time=3600

autostart=true

autorestart=true

stopasgroup=true

killasgroup=true

user=forge

numprocs=8

redirect_stderr=true

stdout_logfile=/home/forge/app.com/worker.log

stopwaitsecs=3600

Next, we will start supervisor with below commands:

sudo supervisorctl reread

sudo supervisorctl update

sudo supervisorctl start laravel-worker:*

Now you can check it, from your end.

I hope it can help you...

#Laravel 11