Search

Laravel 8 send Bulk Mail in Background using Queue

post-title

While working on functionality which takes long time to complete like sending multiple mails, uploading huge data. You can't use synchronous request to process the task. You need to perform async request which works in background process. Laravel provides easy way to process the task using Laravel Queue. This will process all the task in the background, so your application always stay free to give response to users.

In this article, we will send bulk mails using Laravel Queue and Jobs. We will start step by step from the scratch. Follow the below steps to start with tutorial:

  • Step 1: Create Laravel application
  • Step 2: Setup Laravel application
  • Step 3 : Create migration and queue table
  • Step 4: Create routes and Controller
  • Step 5: Create new Job
  • Step 6:Create blade file

Note: You need to have Composer installed to create Laravel application. It also helps to install and manage PHP packages.

Step 1: Create Laravel application

Of course the first step is to create fresh Laravel application. Open the Terminal and go through the directory where you wan to create the project. Then run the composer command to create new Laravel project.

composer create-project laravel/laravel sendmail

When the project installation completes, go to the project root directory.

cd sendmail

Step 2: Setup Laravel application

Now we need to setup email credentials to send emails. Now open the project in Text Editor and open .env environment file and set email credentials of your mail server.

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_passowrd
MAIL_ENCRYPTION=tls

We will use database driver for queue. Also change QUEUE_DRIVER to database

QUEUE_DRIVER=database

Step 3 : Create migration and queue table

If you want to add database as queue driver, you need to create queue table. Run the below commands one by one to create queue table.

php artisan queue:table

php artisan migrate

Step 4: Create routes and Controller

In this step, we will create routes and controller file. Open routes/web.php file and add the routes to send email.

<?php

use App\Http\Controllers\MailController;

Route::get('send-mail', [MailController::class, 'sendMail'])->name('sendMail');

To handle the route, create new controller class using artisan command.

php artisan make:controller MailController

This will create new controller class at app/Http/Controllers/MailController.php. Open the controller file and add the method to handle route.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MailController extends Controller
{
    public function sendMail(Request $request)
    {
        $mail_data = [
            'subject' => 'New message subject.'
        ];
        
        $job = (new \App\Jobs\SendEmail($mail_data))
                ->delay(now()->addSeconds(2)); 

        dispatch($job);
        
        dd("Job dispatched.");
    }
}

Step 5: Create new Job

We have created controller to send mails to Job and dispatch. We also need to create Job to handle it. Run the command to handle it.

php artisan make:job SendEmail

This will create new Job class at app/Jobs directory. Now open Job class and add the below code in it.

<?php

namespace App\Jobs;

use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    
    protected $mail_data;

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

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

        foreach ($users as $key => $value) {
            $input['email'] = $value->email;
            $input['name'] = $value->name;
            
            \Mail::send('mails.mail', [], function($message) use($input){
                $message->to($input['email'], $input['name'])
                    ->subject($input['subject']);
            });
        }
    }
}

We will send emails to all users table data. So you need to add few records in users table.

Step 6:Create blade file

To send email, we need to create email blade template which will be send with email. Create blade file at resources/views/mails/mail.blade.php.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Test mail</title>
</head>
<body>
    <h1>This is header</h1>
    <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>
</body>
</html>

That's all. Now all you have to do is start the Laravel server using artisan command php artisan serve and run the URL http://localhost:8000/send-mail. This will queue the Job in database and start dispatching. Alternatively you can manually dispatch job using command:

php artisan queue:listen

I hope you liked the article. Thank you for giving time to read the article.