5

We are trying to send bulk email (100k) with PHP Laravel framework. Which way is the correct way to send bulk email with Laravel queue?

Case 1.

//controller
public function runQueue(){    
    dispatch(new ShootEmailJob());
}

//job 
public function handle(){
        $emails = EmailList::get(['email']);

        foreach($emails as $email){
            Mail::to($email)->send();
        }
 }

Case 2.

//controller
public function runQueue(){

    $emailList = EmailList::get(['email']);

    foreach($emailList as $emailAddress){
        dispatch(new ShootEmailJob($emailAddress->email));
    }
}

//job    
 public function handle(){
    Mail::to($emailAddress)->send(new ShootMail($emailAddress));
 }

Which one is the correct approach case 1 or case 2?

Mithun
  • 351
  • 1
  • 3
  • 7

1 Answers1

5

The first approach will first fetch all emails and then send them one by one in one "instance" of a job that is run as a background process if you queue it.

The second approach will run n "instances" of jobs, one for each email on the background process.

So performance-wise option 1 is the better approach. You could also wrap it in a try - catch block in case of exceptions so that the job does not fail if one of the emails fails, e.g.:

try {

     $emails = EmailList::get(['email']);

    foreach($emails as $email){
        Mail::to($email)->send();
    }

} catch (\Exception $e) {
   // Log error
   // Flag email for retry
   continue;
}
Sasa Blagojevic
  • 2,110
  • 17
  • 22