How to Send Email using Queue in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to send email using queue in laravel.

 

How to send email using queue in laravel

To send email using queue in Laravel, follow these steps:

 

Step 1 - Configure the mail settings in the .env file.

 

Step 2 - Create a new job by running the command php artisan make:job SendEmail.

 

Step 3 - In the SendEmail job class, define the handle() method to send the email using Laravel's Mail facade. For example:

public function handle()
{
    $email = new ExampleEmail(); // replace with your email class
    Mail::to($this->user->email)->send($email);
}

 

Step 4 - In the controller or wherever you want to send the email, dispatch the job instead of sending the email directly. For example:

public function sendEmail(Request $request)
{
    $user = Auth::user();
    dispatch(new SendEmail($user));
    return redirect()->back();
}

 

Step 5 - Configure the queue driver in the .env file. For example:

QUEUE_CONNECTION=database

 

Step 6 - Run the migration to create the necessary table for the queue:

php artisan queue:table
php artisan migrate

 

Step 7 - Start the queue worker:

php artisan queue:work

 

The queue worker will now process the jobs in the background, sending the emails asynchronously.

Comments 0

Leave a comment