Laravel 10 Send Mail using Queue Example

Mar 11, 2023 . Admin


Hi Dev,

in this short tutorial we will cover an send email using queue in laravel 10. i explained simply step by step how to send mail using queue in laravel 10. you'll learn how to send mail using queue in laravel 10. we will look at example of laravel 10 send mail with queue.

Here,i will give you a simple and easy example how to use implement laravel 10 send email using queue simply follow my all steps.

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2: Create Mail Class with Configuration

In this second step we will create a mail class TestQueueMail following bellow command.

php artisan make:mail TestQueueMail

After successfully run above command go to "Mail" folder in your laravel project directories you can copy this code and put your mail class.

app/Mail/TestQueueMail.php
<?php
  
namespace App\Mail;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
  
class TestQueueMail extends Mailable
{
    use Queueable, SerializesModels;
  
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
          
    }
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.test');
    }
}

So, now we require to create email view using blade file. So we will create simple view file and copy bellow code om following path.

/resources/views/email/test.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Send Mail using Queue Tutorial - Mywebtuts.com</title>
</head>
<body>
   
<center>
<h2 style="padding: 23px;background: #E6F3E5;border-bottom: 6px #DB10286 solid;">
    <a href="https://mywebtuts.com">Visit Our Website : Mywebtuts.com</a>
</h2>
</center>
  
<p>Hi, Sir</p>
<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>
  
<strong>Thank you Sir. :)</strong>
  
</body>
</html>

After configuration of view file, we have to setup for email send, So let' set configuration in .env file:

.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Step 3 : Queue Configuration

In this third step we will make configuration on queue driver so first of all, we will set queue driver "database". You can set as you optate withal we will define driver as Redis additionally. So here define database driver on ".env" file:

.env
QUEUE_CONNECTION=database

After that we need to generate migration and create tables for queue. So let's run bellow command for queue database tables:

Generate Migration:
php artisan queue:table
Run Migration:
php artisan migrate
Step 4 : Create Queue Job

So, in this step we will create queue job bey following command, this command will create queue job file with Queueable. So let's run bellow command:

php artisan make:job SendEmailJob

now you have SendEmailJob.php file in "Jobs" directory. So let's see that file and put bellow code on that file.

app/Jobs/SendEmailJob.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\TestQueueMail;
use Mail;
  
class SendEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  
    protected $details;
  
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }
  
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $email = new TestQueueMail();
        Mail::to($this->details['email'])->send($email);
    }
}
Step 5 : Create Routes

Here, this time to use and test created queue job, so let's simple create route with following code for testing created queue.

routes/web.php
Route::get('email-test', function(){
  
    $details['email'] = 'your_email@gmail.com';
  
    dispatch(new App\Jobs\SendEmailJob($details));
  
    dd('done');
});

Next, you must have to run following command to see queue process, you must have to keep start this command:

php artisan queue:work

You will see layout as like bellow if queue is works:

Output: Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/email-test
Output: Keep Laravel Queue System Running on Server:

As we know we must need to keep running "php artisan work" command on the terminal because then and then queue will work. so in server, you must have to keep running using Supervisor. A supervisor is a process monitor for the Linux operating system, and will automatically restart your queue:work processes if they fail.

So let's install Supervisor using bellow command:

Install Supervisor:
sudo apt-get install supervisor

Next, we need to configuration file on supervisor as below following path, you can set project path, user and output file location as well:

/etc/supervisor/conf.d/laravel-worker.conf
[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

Next, we will start supervisor with below commands:

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

Now you can check it, from your end.

It will help you...

#Laravel 10