How to send Mails Using Queues in Laravel

I have recently spent some time trying with Laravel queue system, in this tutorial I am going to show you how to get started with the implementation of queues using database queue driver.

Let’s start. In order to use the database queue driver, you will need a database table to hold the jobs. To generate a migration that creates this table, run the queue:table Artisan command. Once the migration is created, you may migrate your database using the migrate command:

Above migration will create “jobs” table with following structure –

In order to use Laravel 5’s mail functionality, it first needs to be configured. Look at the mail settings that come out of the box in the .env file.

I am going to use Gmail SMTP settings, here are my confirmations –

Now open you config/mail.php and change the address and name values to use env config values.

Now you can send emails using configured SMTP servers as below shown, this tutorial assumes that you have basic knowledge of laravel.

You may notice there will be a slight delay in receiving a response of success or failure because of Email sending. This delay can be especially long when you are using the SMTP mail driver.

To avoid this delay we are going to use Queues here. Queues allow you to defer the processing of time-consuming tasks, such as email sending. Queues allow your web requests to respond quicker to the user.

Laravel providing several different queue implementation, however, we are going to use Database driver as I told in the post beginning.

Most of the configurations we have already completed by creating jobs table. One final step is, edit .env and change the QUEUE_DRIVER setting from sync to database.

To queue the email, there is only a single small change to make. replace your Mail::send() method with Mail::queue() that is it, now laravel will queue all the emails.

Full code after change –

we need to run the background watching for handling items arriving in the queue. Laravel includes an Artisan command that will run new jobs as they are pushed onto the queue. You may run the listener using the queue:listen command:

That is it.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
DMCA.com Protection Status