How to send multiple emails in Laravel using queue?
How to send multiple emails in Laravel using queue?

In this part of the Laravel tutorial, we will teach you how to send multiple emails in Laravel. As you know, we can easily send emails with the help of Laravel MAil class; But if we want to send them in bulk, sending them one by one will take a lot of time, and if we want to use the loop, for example, not only will it take a long time, but during this time we will not be able to do anything else. So if we want to send bulk emails, we need to use the Laravel queue. With the help of the queue, we can do the process of sending emails in the background and do other things during the prossess.

In this post, we will teach you how to send bulk emails step by step. If you are not familiar with how to send a single email, you can refer to this post:  "How to send an email in Laravel?".

  • Step 1: Configure the env file

.env

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_gmail@gmail.com
MAIL_PASSWORD=your_gmail_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_gmail@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
  • Step 2: Create a Route

In this step, we will create the web route needed to send bulk emails by using the queue.

Route::get('send/mail', [SendMailController::class, 'send_mail'])->name('send_mail');
  • Step 3: Create a Job Table

Now, we create the "jobs" table in the database, so copy the following command and run it in your terminal.

php artisan queue:table

php artisan migrate​
  • Step 4: Create a controller

In this step, we will create the SendMailController and  then we will add the following commands to it.

app> http >Controllers

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SendMailController extends Controller
{
    public function send_mail(Request $request)
    {
    	$details = [
    		'subject' => 'Test Notification'
    	];
    	
        $job = (new \App\Jobs\SendQueueEmail($details))
            	->delay(now()->addSeconds(2)); 

        dispatch($job);
        echo "Mail send successfully !!";
    }
}
  • Step 5: Create a Job

Now we will create the SendQueueEmail.php file in app> Jobs. To do this, just run the following command in your terminal.

php artisan make:job SendQueueEmail

You will see that the mentioned file will be created as follows.

app> Jobs

<?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\User;
use Mail;

class SendQueueEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $details;
    public $timeout = 7200; // 2 hours

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $data = User::all();
        $input['subject'] = $this->details['subject'];

        foreach ($data as $key => $value) {
            $input['email'] = $value->email;
            $input['name'] = $value->name;
            \Mail::send('mail.Test_mail', [], function($message) use($input){
                $message->to($input['email'], $input['name'])
                    ->subject($input['subject']);
            });
        }
    }
}
  • Step 6: Create Blade View for Email

Create the Test_mail.blade.php file in resources> views> mail and put the following commands in it.

resources> views> mail

<!DOCTYPE html>
<html>
<head>
    <title>www.maryam-hajireza.ir</title>
</head>
<body>
    <h1>Testing Bulk Email Using Que</h1>
    <p>Hello this is a test email</p>
   
    <p>Thank you</p>
</body>
</html>

Finally, enter the following command in the terminal to send the emails.

php artisan queue:listen

In case you want to start the queue in a controller you can use the following code for your controller.

<?php
   namespace App\Http\Controllers;

   use Illuminate\Http\Request;
   use App\Jobs\SendQueueEmail;

   class EmailController extends Controller
   {
      public function sendEmail()
      {
         $emailJob = new SendQueueEmail();
         dispatch($emailJob);
      }
   }