Laravel Mail Sending with Queues
Almost
every application we need mail sending functionality. In laravel mail sending
functionality work out of the box. When we try to send mail it takes time
depending on mail sever speed. So in this case user should wait unit mail
successfully sent which is not good for user experience. That’s why we need
send mail through queue. In this article we will learn who to send mail using
laravel queue.
By default laravel 10 there is no queue processing table in database. We have to create queue table following the artisan command.
php artisan queue:table
php artisan migrate
after
successful migration we have to change queue_connection=sync to
queue_connection=database. Open your .env file and make QUEUE_CONNECTION = database
Let’s create a job for sending mail using artisan command:
php artisan make:job ContactMailSendJob
Past bellow code.
<?php
namespace App\Jobs;
use App\Mail\MailSendExample;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
class ContactMailSendJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(public array $data){}
public function handle(): void
{
Mail::to('rasel.laravel@gmail.com')
->send(new MailSendExample($this->data));
}
}
Here
MailSendExample is a laravel mailable if you don’t know about mailable please
read this article
How to send mail using laravel mailable
we should dispatch this job from any controller or route let’s look.
<?php
namespace App\Http\Controllers;
use App\Jobs\ContactMailSendJob;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class MailSendController extends Controller
{
public function send(Request $request) : RedirectResponse
{
// please make validation before next line which is best prectices
$data = [
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'message' => $request->message
];
dispatch(new ContactMailSendJob($data));
return redirect()->back()->with('success','Mail has been sent successfully');
}
}
Now everything is looks good. Let’s run queue using artisan command:
php artisan queue:work
Happy Coding.
Read More: Right way to send mail in laravel