Email Send Using Queue In Laravel

  • 24-05-2022
  • 1493
  • Laravel 8
  • Haresh Chauhan

What Is Laravel Queue?

Laravel Queue is reducing delay at a time when you sending a request to and save to the server and later time will be performing a job, In another word we can say that consuming thing will save data into database serve and after the response it will perform an action. Simple can say reduce delay time when you send API request.

How To Mail Send Using Queue?

In this post you will learn how to send email using the queue, It is a powerful tool to send a mailing. So we just need a little config for the used queue in laravel. Also, it is related with laravelJob using laravel job mail will be stored into the database and later or when you wish you can start queue using queue: start and mail will send to every user which stored into the database.

The queue is one of the powerful tool after Authentiation In the terms of laravel.

Apart from that queue, you can use with many Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"

In this post, we will use the database driver to send mail to the user and the database server will be MYSQL, Well not worry will see in this post ahead of the whole configuration how to use. So the first step toward starting implement is clone project.

Step: 1 Install Laravel Project

Go to your directory and install the laravel project using the below command. Before must installed composer in your system.

composer create-project laravel/laravel:^8.0 mail-example

Step: 2 Make Mail

Using the below command will create a mail file inside App\Mail\SendMail.

php artisan make:mail SendMail

__construct message will receive form $message and append to Private $message for make it global in the class.

Also i have made a mail.blade.php file for print file in template.

Added Subjects and from and send data variable inside the blade file.

App\Mail\SendMail.php

<?php
namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class SendMail extends Mailable
{
    use Queueable, SerializesModels;

    private $message;

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

    /**
        * Build the message.
        *
        * @return $this
        */
    public function build()
    {
        return $this->view('mail')
            ->from('webappfix@gmail.com')
            ->subject('Queue Mail Send Test')
            ->with(['data' => $this->message]);
    }
}

This will be your SendMail.php mail file.

Step: 3 Create Blade File

resources/views/mail.blade.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Webappfix</title>
    </head>
    <body>
        {{ $data }}
    </body>
</html>

This will be your Email template file. This content will show up in your email inbox. This should have a stylish and modern look.

Step: 4 Make Job

The below command will create a Job for mail sent to the queue server and stored in the database.

php artisan make:job MailSendJob

__construct will receive message from where the MailSendJob called and this will append to private $message veriable.

App\Jobs\MailSendJob.php

<?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 Mail;

use App\Mail\SendMail;

class MailSendJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $message;

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

    /**
     * Execute the job.
     *
     * @return void
     */

    public function handle()
    {
        Mail::to('webappfix@gmail.com')->send(new SendMail($this->message));
    }
}

Step: 5 .env Config Set

.env

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=04de5bd68a77ff
MAIL_PASSWORD=90c17cef17d0ca
MAIL_ENCRYPTION=tls

Database Connection also set. laravel this is my database which i made in MYSQL.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

This is your queue driver. This will database and all that queue jobs will store in the database temporarily. once you start the queue will delete one by one job from jobs table.

QUEUE_CONNECTION=database

Step: 6 Cache Clear

After change in .env file i might have cache with old config in your project. So we must need to clear cache before go ahead.

php artisan cache:clear

And also if you already started your development server please restart for cache: clear.

Step: 7 Generate Queue Job Table

User below command queue table will generate for Job. This table will you can seed in your migrations file table named with jobs.

php artisan queue:table 

database/migrations

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateJobsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('queue')->index();
            $table->longText('payload');
            $table->unsignedTinyInteger('attempts');
            $table->unsignedInteger('reserved_at')->nullable();
            $table->unsignedInteger('available_at');
            $table->unsignedInteger('created_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('jobs');
    }
}

This migration file will be generated by the above command entered.

Step: 8 Migrate Database

Once generate jobs migration enter the below command in your terminal this will migrate all tables in your database with default laravel table and jobs table.

php artisan migrate

Step: 9 Make Controller

Enter the below command and create a controller for the mail send test. I have make EmailSendController.

php artisan make:controller EmailSendController

This is my EmailSendController and added one method which is Sendmail. We will engage this controller method with a web route for run this method.

App\Http\Controllers\EmailSendController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Jobs\MailSendJob;

class EmailSendController extends Controller
{
    public function sendMail()
    {
        $message = 'This is queue test message from webappfix';

        dispatch(new MailSendJob($message));

        dd('Email Successfully added in queue');
    }
}

Step: 10 Make Route

Create email-send-queue url and that url will run sendmail method in side EmailSendController.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\EmailSendController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('email-send-queue',[EmailSendController::class,'sendMail']);
        

Step: 11 Start Development Server

This command will start your development server for this laravel project with the hosthttp://localhost:8000.

php artisan serve

Step: 12 Mail Send Url

Run this URL in your browser and check in your database jobs table. there were you will find a record.

http://127.0.0.1:8000/email-send-queue

Step: 13 Start Queue Job

Start Queue job using the below command in your terminal and you will see there something output.

php artisan queue:work
image

image

image

Thanks for reading our post...


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :