Saturday, August 13, 2016

Laravel 5.2 using queue to send email

To sent email after desired number of second, first change the .env file as follow.
  • First provide database credential
  • set
    QUEUE_DRIVER=sync to
    QUEUE_DRIVER=database
Normally , QUEUE_DRIVER=sync tries to sent email immediately and if we set it as database, we can sent email after desired number of seconds. then,
  • give the email credential , from which you want to sent email
Here i will be using smtp server , so to sent email we have to change gmail setting and give permission to access email account from less secured apps. Here is the link to set access from less secure apps click turn on and you are ready to go. Now go tho the queue.php file in config folder and find the array key database. Here is the information we get:
'database' => [
    'driver' => 'database',
    'table'  => 'jobs',
    'queue'  => 'default',
    'expire' => 60,
],
From this data, we can see that to use database as queue driver we have to create a table called jobs. To create this table, we have to run following command
php artisan queue:table
This command will create a migration file which will create a table called jobs with necessary fields. Now we will create a table to track failed jobs. To create this table we have to run following command:
php artisan queue:failed-table
This command will create a migration file , which will create a new table called failed_jobs Now run following command to create table using this migration files.
php artisan migrate
Now, in your .env file set following information
MAIL_DRIVER=smtp
#MAIL_HOST=mailtrap.io
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=*********
MAIL_PASSWORD=*********
MAIL_ENCRYPTION=tls
MAIL_FROM=*********
MAIL_NAME=Dushor Alo
Now go to mail.php file on config folder. Comment out this line
'from' => ['address' => null, 'name' => null],
and use this code
'from' => ['address' => env('MAIL_FROM'), 'name' => env('MAIL_NAME')],
And other settings are
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
Now go to routes.php file and add following lines
Route::get('send/mail',function(){
    $user=['name'=>'Rashed','email'=>'xyz@gmail.com'];

    \Illuminate\Support\Facades\Mail::later(5,'emails.reminder', ['user' => $user],function ($m) use ($user) {
        $m->from(env('MAIL_FROM'), 'Your Testing Application');

        $m->to($user['email'], $user['name'])->subject('Your Reminder!');
    });
});
In here we are using Mail::later(5), which represents that email will be sent 5 seconds later. So our setup is done , and if we browse send/mail we will receive email after 5 seconds.

0 comments:

Post a Comment