How To Send Mail Using Queue In Laravel 10

In this article, we will see how to send mail using a queue in laravel 10. Here, will learn about laravel 11 sends mail using a queue example. Many times we can see many processes take more time to load like bulk email sending, invoice sending, etc.

In laravel 10 and laravel 11, you can easily send mail using a queue. Laravel's queue configuration options are stored in your application's config/queue.php configuration file.

Whenever you are sending an email for verification then it loads time to send mail because it is services. You can use the queue if you don't want to wait for the user to send an email or other processes on loading the server-side process.

In laravel 10/11 send mail using a queue example we will set up the mailtrap for sending an email. Laravel queues provide a unified queueing API across a variety of different queue backends, such as Amazon SQSRedis, or even a relational database.

So, let's see the laravel 10 queue job, send email using queue in laravel 10 and laravel 11, and how to send email in laravel 10 and laravel 11 using a queue.

Step 1: Install Laravel 10/11

In this step, we will install the laravel 10 application using the composer command.

composer create-project --prefer-dist laravel/laravel laravel_10_send_mail

 

 

Step 2: Create Mail Setup

Now, we will run the below command in the terminal and create the mail.

php artisan make:mail SendEmailQueueDemo

Now, you will find the new Mail folder in the app directory with the SendEmailQueueDemo.php file. So, add the below code to this file.

app/Mail/SendEmailQueueDemo.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 SendEmailQueueDemo extends Mailable
{
    use Queueable, SerializesModels;
    /**
     * Create a new message instance.
     */
    public function __construct()
    {
          
    }
  
    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'How To Send E-mail Using Queue In laravel 10',
        );
    }
  
    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'email.demo',
        );
    }
  
    /**
     * Get the attachments for the message.
     *
     * @return array

     */
    public function attachments(): array
    {
        return [];
    }
}

After that, we need to create an email view using a blade file. So, we will create demo.blade.php following the path.

 

 

resources/views/email/demo.blade.php

<!DOCTYPE html>
<html>
<head>
	<title>How To Send Mail Using Queue In Laravel 10/11 - Techsolutionstuff</title>
</head>
<body>
   
<center>
<h2>
	<a href="https://techsolutionstuff.com">Visit Our Website : Techsolutionstuff</a>
</h2>
</center>
  
<p>Hello,</p>

<p>This is a test mail. This mail is sent using queue listen in laravel 10 and laravel 11.</p>  

<strong>Thanks & Regards.</strong>

</body>
</html>

Now, we will configure of view file, which we have to set up for email send, So let's configure it in the .env file.

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

 

Step 3: Configuration of Queue

Now, we are setting up the configuration on the queue driver. So, we will set the queue driver "database". Also, we will define the driver as Redis. So, here we will define the database driver on the .env file.

QUEUE_CONNECTION=database

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

php artisan queue:table

Now, run the migration in your terminal.

php artisan migrate

 

 

Step 4: Create a Queue Job

In this step, we will create a new queue job. So, run the below command in your terminal.

php artisan make:job SendEmailQueueJob

After running the above command the SendEmailQueueJob.php file is created.

app/Jobs/SendEmailQueueJob.php

<?php
  
namespace App\Jobs;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Mail\SendEmailQueueJob;
use Mail;
  
class SendEmailQueueJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  
    protected $send_mail;
  
    /**
     * Create a new job instance.
     */
    public function __construct($send_mail)
    {
        $this->send_mail = $send_mail;
    }
  
    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $email = new SendEmailQueueDemo();
        Mail::to($this->send_mail)->send($email);
    }
}

 

 

Step 5: Test Queue Job

Now, we will check the queue job. So, add the below code to the web.php file and dispatch the queue job.

routes/web.php

Route::get('send/email', function(){
  
	$send_mail = 'test@gmail.com';
  
    dispatch(new App\Jobs\SendEmailQueueJob($send_mail));
  
    dd('send mail successfully !!');
});

Now, clear the config cache using the below command for sending mail with a queue in laravel 10.

php artisan config:clear

 

Step 6: Run Laravel 10 Application

Now, run this laravel 10 send mail using the queue example with the artisan command.

php artisan serve

After that, run the following command.

php artisan queue:listen

OR

php artisan queue:work

 

Laravel Queue System Running on Server

In production, you need a way to keep your queue:work processes running. A queue:work process may stop running for a variety of reasons, such as an exceeded worker timeout or the execution of the queue:restart command.

For this reason, you need to configure a process monitor that can detect when your queue:work processes exit and automatically restart them. In addition, process monitors can allow you to specify how many queue:work processes you would like to run concurrently.

The supervisor is a process monitor commonly used in Linux environments and we will discuss how to configure it in the following documentation.

So, let's install Supervisor using the following command.

Installing supervisor

Supervisor is a process monitor for the Linux operating system, and will automatically restart your queue:work processes if they fail. To install Supervisor on Ubuntu, you may use the following command

sudo apt-get install supervisor

 

Configuring supervisor

Supervisor configuration files are typically stored in the /etc/supervisor/conf.d directory. Within this directory, you may create any number of configuration files that instruct the supervisor on how your processes should be monitored. 

For example, let's create a laravel-worker.conf file that starts and monitors queue:work processes.

[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

 

Starting supervisor

Once the configuration file has been created, you may update the Supervisor configuration and start the processes using the following commands.

sudo supervisorctl reread
 
sudo supervisorctl update
 
sudo supervisorctl start laravel-worker:*

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS