{{ $data['title'] }}
Published at: {{ $data['published_at'] }}
Check out the full blog post here.
In this blog, we discuss the way to send emails with Laravel’s queue job. Sending emails via queues will improve the overall performance and users revel in your software by sending emails inside the background. We will talk about the way to set up e-mail configurations, create mailable lessons, define jobs, and dispatch them with a sensible example.
Overview Of Queue Jobs in Laravel
A queue is a very nice Larvel feature that can help you to delay the processing of a time-consuming task like dispatching an email. Jobs are an abstraction layer for individual tasks that are appended to a queue that is processed outside of the request cycle, which will make your application faster by delegating these tasks to something that is not in the main request. Using queue jobs in Laravel to send emails will keep your application responsive and help dispatch emails efficiently as well.
Set up the new Laravel project to use this blog, if you do not create a new Laravel project, create it by running the following command:
After that, navigate to your project directory:
Laravel supports several queue drivers by default. From a technical standpoint, the driver is where the queued jobs will be stored until they are handled. Here is a quick comparison of some of the available drivers:
1. Sync:
The sync driver handles jobs immediately. It’s a great option for local development and testing, but it’s not suitable for production.
Filename: .env
QUEUE_CONNECTION=sync
2. Database:
The database driver stores jobs on a relational database. The driver is perfect for production and fairly easy to configure.
Filename: .env
QUEUE_CONNECTION=database
In Laravel, you may create a jobs table Executing the below command:
This command will create a jobs table in your database.
3.Other Drivers
1. Redis:
To use Redis as the queue driver in Laravel, you need to configure it in the config/queue.php file:
Filename: queue.php
'connections' => [ 'redis' => [ 'driver' => 'redis', 'connection' => 'default', // The Redis connection to use 'queue' => env('REDIS_QUEUE', 'default'), 'retry_after' => 90, 'block_for' => null, ], ],
Also, define the Redis connection details in your .env file:
Filename: .env
QUEUE_CONNECTION=redis REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379
2. Amazon Simple Queue Service (SQS):
Configure SQS as the queue driver in config/queue.php:
Filename: queue.php
'connections' => [ 'sqs' => [ 'driver' => 'sqs', 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), 'queue' => env('SQS_QUEUE', 'your-queue-name'), 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), ], ],
QUEUE_CONNECTION=sqs SQS_QUEUE={your-queue-name} AWS_ACCESS_KEY_ID=your-{access-key-id} AWS_SECRET_ACCESS_KEY={your-secret-access-key} AWS_DEFAULT_REGION=us-east-1
Create a mailable class that will be used to send emails.
The command creates a new class in app/Mail/BlogPostPublished.php.
Filename: BlogPostPublished.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 BlogPostPublished extends Mailable { use Queueable, SerializesModels; protected $data; public $subject; public function __construct($data, $subject) { $this->data = $data; $this->subject = $subject; } public function envelope(): Envelope { return new Envelope( subject: $this->subject, ); } public function content(): Content { return new Content( view: 'blog-mail', with: [ 'data' => $this->data, ], ); } public function attachments(): array { return [ // Here, you can attach your file with something like // Attachment::fromPath($this->filepath), ]; } }
The previous command generates a new class in a file named SendEmailJob.php under the app/Jobs/ Modify the created class as follows:
Filename: SendEmailJob.php
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class SendEmailJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $mail_to, $template; public function __construct($mail_to, $template) { $this->mail_to = $mail_to; $this->template = $template; } public function handle() { try { Mail::to($this->mail_to)->send($this->template); } catch (\Exception $e) { Log::error('Mail Sending Failed | ' . $e->getMessage()); } } }
You now need to generate a view to be sent in the email. Run this command:
The preceding command creates a new view file, resources/views/blog-mail.blade.php, containing the Email HTML content.
Filename: blog-mail.blade.php
{{ $subject }} {{ $subject }}
To generate a controller Run the following:
This command will create a new controller file named BlogPostPublishedController.php in the app/Http/Controllers directory.
Inside this controller, we will call BlogPostPublished and SendEmailJob and send the emails using this.
Filename: BlogPostPublishedController.php
<?php namespace App\Http\Controllers; use App\Jobs\SendEmailJob; use App\Mail\BlogPostPublished; use Illuminate\Http\Request; class BlogPostPublishedController extends Controller { public function BlogPostPublished(Request $request) { $staticPostData = [ 'title' => 'Streamlining Laravel: 10 Game-Changing Practices You Need to Know', 'blog-link' => "https://dolphinwebsolution.com/blog/laravel-10-game-changing-practices/", 'email' => "bhadresh@gmail.com", 'author' => 'Bhadresh Kotadiya', 'published_at' => 'May 15, 2024', ]; $subject = "Your Blog Post is Live! Check it Out Now"; $template = new BlogPostPublished($staticPostData, $subject); SendEmailJob::dispatch($staticPostData['email'], $template); dd("We have emailed subscribers about your new blog post!"); } }
use App\Http\Controllers\BlogPostPublishedController; Route::get('blog/published', [BlogPostPublishedController::class, 'BlogPostPublished'])->name('blog.published');
You can find the whole source code here – Github Repository.
In conclusion, sending an e-mail by way of queuing Laravel’s jobs for notifications allows you to fast and effectively method historical past jobs. The application remains quick and user-friendly by utilizing various capabilities to make certain that it operates effectively. Following the above steps to integrate this feature into the Laravel initiatives will enhance the machine’s performance and value to an outstanding quantity.
Dolphin Web Solution has dedicated and skilled Laravel developers. Are you looking for a Laravel expert? If yes, then without wasting a second, contact us and hire a Laravel developer. We ensure to provide the best and most proficient Laravel developers who can meet your requirements.
Click one of our contacts below to chat on WhatsApp