Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Send emails in queue in Laravel

Tags:

email

laravel

I tried to send email in a queue, but not working.

Mail::queue('emails.mailsubscribe', ['email'=>$email], 
    function($message) use($email)
    {
       $message->to('[email protected]')->subject('Subscribe: XXXXX');
    });
like image 832
nitinsridar Avatar asked Mar 14 '18 11:03

nitinsridar


1 Answers

In order to make Laravel 5/6 full queuing you need make below steps:

  1. php artisan queue:table (for jobs)
  2. php artisan queue:failed-table (for failed jobs)
  3. php artisan migrate
  4. Set in .env QUEUE_DRIVER=database
  5. Fire: php artisan config:cache
  6. Fire queuing: php artisan queue:work database --tries=1 (after all uncompleted tries it will be registered in failed jobs table)

Since sending email messages can drastically lengthen the response time of your application, many developers choose to queue email messages for background sending. Laravel makes this easy using its built-in unified queue API. To queue a mail message, use the queue method on the Mail facade after specifying the message's recipients:

Mail::to($request->user())
    ->cc($moreUsers)
    ->bcc($evenMoreUsers)
    ->queue(new OrderShipped($order));

This method will automatically take care of pushing a job onto the queue so the message is sent in the background. Of course, you will need to configure your queues before using this feature.

If you wish to delay the delivery of a queued email message, you may use the later method. As its first argument, the later method accepts a DateTime instance indicating when the message should be sent:

$when = now()->addMinutes(10);

Mail::to($request->user())
    ->cc($moreUsers)
    ->bcc($evenMoreUsers)
    ->later($when, new OrderShipped($order));

If you have mailable classes that you want to always be queued, you may implement the ShouldQueue contract on the class. Now, even if you call the send method when mailing, the mailable will still be queued since it implements the contract:

use Illuminate\Contracts\Queue\ShouldQueue;

class OrderShipped extends Mailable implements ShouldQueue
{
    //
}
like image 171
Adam Kozlowski Avatar answered Nov 03 '22 23:11

Adam Kozlowski