15 Min Read

How to Send Emails Using Queue Jobs in Laravel?

Written by Bhadresh Kotadiya

Jun 25, 2024

How to Send Emails Using Queue Jobs in Laravel?

Summary :

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.

Steps to Send Emails in the Background with Laravel

Step-1. Set Up the Laravel Project

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:

  • composer create-project –prefer-dist laravel/laravel send-mail

After that, navigate to your project directory:

  • cd send-mail

Step-2. Setup Queue Configuration:

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:

  • php artisan queue:table
  • php artisan migrate

This command will create a jobs table in your database.

3.Other Drivers

1. Redis:

  • In Laravel, you can also configure Redis as a queue motive force that allows storing queued jobs and managing them in the history.
  • 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
        
  • Ensure you have configured correctly based on your installation.

2. Amazon Simple Queue Service (SQS):

  • Laravel also supports SQS as a queue driver. This will allow the use of the available AWS infrastructure to manage message queuing.
  • 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'),
               ],
      ],
            
  • You also need to define your AWS credentials and SQS queue details in .env file.
    Filename: .env

    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
    

Step-4. Create a Mailable Class:

Create a mailable class that will be used to send emails.

  • php artisan make:mail BlogPostPublished
  • 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),
            ];
        }
    }
        

Step-5. Create a Job:

  • You can create only a single job (e.g., SendEmailJob) to manage all email-sending activities in a single location in the Laravel application.
  • One job can send several types of emails with the same single job, you only need to pass the data it requires, such as the post email mailable classes and any other extras.
  • Use this command to generate a job that will handle sending the email in the background:
    • php artisan make:job SendEmailJob

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());
        }
    }
}
    

Step-6. Create View File

You now need to generate a view to be sent in the email. Run this command:

  • php artisan make:view blog-mail

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 }}

Thumbnail Image

{{ $data['title'] }}

Author Image

Author: {{ $data['author'] }}

Published at: {{ $data['published_at'] }}

Check out the full blog post here.

Step-7. Create a Controller:

To generate a controller Run the following:

  • php artisan make:controller BlogPostPublishedController

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!");
    }
}

Step-8. Add Route in Web.php File:

use App\Http\Controllers\BlogPostPublishedController;
Route::get('blog/published', [BlogPostPublishedController::class,
'BlogPostPublished'])->name('blog.published');

Step-9. Serve your project:

  • Start your project by running php artisan serve.
  • After starting your project with php artisan serve, you can hit the URL(http://127.0.0.1:8000/blog/published) to trigger the mail send functionality. This action will queue the email job and store it in the jobs table because we are using QUEUE_CONNECTION=database.

Serve your project

Step-10. Start the queue worker to process the jobs:

  • When you run php artisan queue:work, all queued jobs are processed, and the emails are sent accordingly.

queue worker
queue worker2

You can find the whole source code here – Github Repository.

Conclusion

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.

Bhadresh Kotadiya

Author

Meet Bhadresh Kotadiya, a skilled Laravel developer known for his passion for fitness, knack for problem-solving, love for reading, and expertise in code debugging. Always ready to take on new challenges. he brings his experience in Laravel development to the table, seamlessly blending it with his current projects.

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out the form below, and one of our technical experts will reach out to you within 12 hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    ×

    Hello!

    Click one of our contacts below to chat on WhatsApp

    × How can I help you?
    TO TOP