How to Send Mail using Jobs and Queues in Laravel
In this article we will learn how to send mail using Jobs and queues in Laravel . Use of Jobs and Queues makes your work much faster , In this article we will send mail using Jobs and Queue . For sending mails i will be using Mailtrap . You can use any other Mail services like Mailgun and Gmail etc .
Why to use Jobs and Queue :
Let me give you an example , suppose you have a button and you want to send a mail whenever the button is clicked . Without jobs and queue , whenever to click on the button it will take some time like 15 - 20 seconds for which the user have to wait .
But with the use of jobs and queue , whenever you click on the button your work will be stored in a table called jobs table in your database and the user don't need to wait for the processing to be completed because when you click on the button it will take less that a second to send your work to the database and whenever the server will be free it will execute your task and it will send the mail .
Table of content :
- Create a project
- Configure MailTrap
- Setup Routes
- View file for sending mail
- Create Job
- Create Mail
- Setup Controller
- Code to send Mail
Step 1 - Create a Project :
First create a Laravel project using the following command .
composer create-project --prefer-dist laravel/laravel Project_Name
Step 2 - Configure Mailtrap :
Before sending mail you need to configure your mail . As i have using MailTrap , You can setup mailtrap as follow .
Mailrtap.io :
Make sure your " .env " file mail configuration matches your Mailtrap.io Credentials .
MAIL_MAILER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=34d7af640c9818 MAIL_PASSWORD=d07708a6993e38 MAIL_ENCRYPTION=tls MAIL_FROM_ADDRESS=studywithkishan@gmail.com MAIL_FROM_NAME="${APP_NAME}"
Change QUEUE_CONNECTION :
Change your queue connection from sync to database .
BROADCAST_DRIVER=log CACHE_DRIVER=file QUEUE_CONNECTION=database SESSION_DRIVER=file SESSION_LIFETIME=120
Step 3 - Setup Routes :
Now setup your routes for your view file where we will provide our email id for sending mail and also the route for sending the mail .
Route::get('/sendmailview','CheckController@sendmailview'); Route::post('/sendmail','CheckController@sendmail');
Step 4 - View file :
sendmail.blade.php :
@extends('layouts.app') @section('content') <div class="row"> <div class="col-4"> </div> <div class="col-4 text-center"> <form method="post" action="{{url('/sendmail')}}"> {{csrf_field()}} <input type="email" name="email" class="form-control"> <button class="btn btn-primary" type="submit">Send Mail</button> </form> </div> <div class="col-4"> </div> </div> @endsection
Step 5 - Create Job :
To implement Jobs and Queue , we first need to create a Job . To create a job use the following command .
php artisan make:job SendEmailJob
The above command will create a job file inside " project_name/app/Jobs/SendEmailjob.php " , now we need to create a it's migration file and to migrate it . For doing this use the following commands .
php artisan queue:table
php artisan migrate
Now the above command will create a " jobs " table in your database .
Step 6 - Create Mail :
Use the following command to create a Mail file for sending mail .
php artisan make:mail SendMail
The above command will create a Mail file inside your " project_name/app/Mail/SendMail.php " .
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; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this->view('mailbody'); //mailbody is the name of the view file you want to set as email body } }
mailbody.blade.php :
@extends('layouts.app') @section('content') <div class="row"> <div class="col-4"> </div> <div class="col-4 text-center"> <form method="post" action="{{url('/sendmail')}}"> {{csrf_field()}} <input type="email" name="email" class="form-control"> <button class="btn btn-primary" type="submit">Send Mail</button> </form> </div> <div class="col-4"> </div> </div> @endsection
Step 7 - Setup Controller :
Now we have to write the code for dispatching the job inside the controller , so that it can send mail .
CheckController.php :
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; use App\Jobs\SendEmailJob; class CheckController extends Controller { public function sendmailview() { return view('sendmail'); } public function sendmail(Request $request) { $email = $request->email; SendEmailJob::dispatch($email)->delay(now()->addSeconds(5)); } }
Note :
Whenever you are writting code for dispatching the job do not forget to use that class at the top like following
use App\Jobs\SendEmailJob;
SendEmailJob.php :
Now we have to write the code for sending mail inside the job file .
<?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\Mail\SendMail; use Illuminate\Support\Facades\Mail; class SendEmailJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $email; /** * Create a new job instance. * * @return void */ public function __construct($email) { $this->email = $email; } /** * Execute the job. * * @return void */ public function handle() { Mail::to($this->email)->send(new SendMail); } }
Note :
While writting code for sending Mail inside the Job file do not forget to use the file classes on the top like the following .
use App\Mail\SendMail; use Illuminate\Support\Facades\Mail;
Now use the following command to start your queue .
php artisan queue:work
That's it . now your job and queue is ready . You can now send mail within a fraction of seconds .
Thank you for reading this article 😊
For any query do not hesitate to comment 💬