Search code examples
laravelemailcronqueuebeanstalkd

Laravel - Send Mail in Future based on condition


I want to send emails to various users based on the schedules they have set.

I read about beanstalkd, queues and Delayed Message Queueing and for now it looks like fitting in:

$when = Carbon::now()->addMinutes($minutes); // i can calculate minutes at this moment
\Mail::to($user)->later($when, new \App\Mail\TestMail);

But i'm not quite sure on few things:

  1. User can cancel a future schedule. In that case how do i cancel an email that's suppose to send in future. Can i set condition somewhere that gets checked before sending the actual email? Tried return false on handle method of \App\Mail\TestMail and it started throwing error

  2. Am i using the right approach. I also read about Scheduler but i don't get how i am going to cancel future emails(if they need to be)


Solution

  • There are many ways to approach this. Personally I would queue the emails on a schedule rather than adding them to the queue for later.

    So you run a scheduled task once a day (or hour, or minute) which runs a query to select which users require an email, then using that result set, you add a job to the queue for each result.

    This way, if a user unsubscribes, you don't have to worry about removing already queued jobs.

    Laravel offers quite a nice interface for creating scheduled jobs (https://laravel.com/docs/5.4/scheduling) which can then be called via a cronjob.