Sunday, June 12, 2016

Laravel Queues | How to send Email using Laravel Queue?

laravel queues



When you send mass emails, it's better to use Queues. Many developers now a days using Queues for sending those mass emails.
Why? 

Because it speeds up web requests to your application. It will help your run the sending e-mail after certain time gap so you can easily keep track whether the job has done or not. So let's stop the discussion and start how you can send email  using laravel Queue.

1. First open your .env file in your project as here we gonna change some configuration for sending mail.

See the before by default .env setting in MAIL section with fresh laravel installation you get. And here we need to change the setting.
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
And after changing the setting we get this:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=youremail@gmail.com
MAIL_PASSWORD=youremailpassword
MAIL_ENCRYPTION=tls
2. Now from your root folder go to Config folder and inside of this open the mail.php as here also we need to change some setting:

Before change of setting with fresh installation we get this in that mail.php file:
<?php

return [

    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
    'port' => env('MAIL_PORT', 587),
    'from' => ['address' => null, 'name' => null],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'sendmail' => '/usr/sbin/sendmail -bs',

];
And after changing the setting we will get this:
<?php

return [

    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 587),
    'from' => ['address' => 'youremail@gmail.com', 'name' =>'YourGmailUserName'],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => false,
];
3. Then we need to focus on Queue. So first of change the .env file setting for QUEUE_DRIVER=sync to QUEUE_DRIVER=database. 

4. Our task in almost done. Now we gonna set the routes.php and make a controller.php to send the email. Let's start with routes

5. In routes.php we need to initialize in which user it will send the user. I have given a demo code you can change with your required code as it's almost same.

 Route::get('/sendMail',[
     'uses' =>'UserController@sendEmail',
     'as' =>'sendMail',       
        ]); 

6. We have to make a view page as we need to send the email with that page only. So here we gonna make a send.blade.php in resources/views folder which we'll send as email.
send.blade.php: 

 <html>
   <head> Email Demo</head>
     <body> 
         <p>Thanks for Registering with User Id</p>
     </body>
</html>

7. Now let's a create a RESTful Resource Controller for sending Email. Here we have created sendEmail controller. 


public function sendEmail(Request $request)
    {
               $user=User::all();
            Mail::queue('send', ['user' => $user], function($m) use ($user)
              {
                    foreach ($user as $user) {
                        $m->to($user->email)->subject('Email Confirmation');
                    }
                 });
   }

ooh ..don't forget to use namespace use Mail; above of your controller.

7. If you want to delay the queued e-mail message, you can user later method.  You need to add a number of seconds by which you want to delay the email  as a first argument to the method


 public function sendEmail(Request $request){
            $user=User::all();
             Mail::later(5, 'send', ['user' => $user], function ($m) use ($user)
            {
                    foreach ($user as $user) {
                       $m->to($user->email)->subject('Email Verification');
                        }    
                });
            }

That's it. It will find list of  user with the User::all()  then it will send the mails to the users.

8. We need to create Queue table in database using following command before click on the route:

php artisan queue:table  
php artisan migrate
9. Before starting the project we need to run  a listener to listen the Queue Request. But I'm gonna introduce with new method as listen is high CPU usage. It's better to use daemon.So Run the following command:
 php artisan queue:work --daemon --tries=3
10. So when we access the sendEmail route it will send email to list of users using these Queue and complete the process.

NB: We can also do the above task creating job and handler method instead of doing in controller and routes. In later section I'm gonna write about it So, stay connected with my blog till then.

Thanks for reading the whole article. Hope you can send Email with Laravel using Queue now with these easy steps. And if you face any problem don't forget to ping me on comment.

Related Articles

0 comments:

Post a Comment