When a certain event is fired, my Laravel based app has to send exactly one transactional email to each user in a mailing list.
Here is the loop code:
$users = User::where('notifiable', 1)->get();
foreach($users as $user) {
$info = [
'email' => $user->email,
'name' => $user->name
];
$data = [
'message' => 'Sample text'
];
Mail::send(['emails.html.notification', 'emails.text.notification',], $data, function($message) use ($info) {
$message
->to($info['email'], $info['name'])
->subject('example')
->from('admin@example.com','Example');
});
}
Unfortunately, several users are receiving the same mail multiple times. I can't figure out what's happening:
The app is using Sendinblue as an external SMTP service. Some hints I got:
Apparently, queuing the email and setting a delayed event has solved the problem.
Now a new job is requested every 10 seconds.
$users = User::where('notifiable', 1)->get();
$counter = 0;
foreach($users as $user) {
$payload = [
'email' => $user->email,
'name' => $user->name,
'message' => 'Sample text'
];
dispatch(new SendNotification($payload))
->delay(now()->addSeconds($counter * 10));
$counter++;
}
Thanks for your support!