Search code examples
phplaravelemailspamsendinblue

Laravel sending each e-mail multiple times


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('[email protected]','Example');
    });

}

Unfortunately, several users are receiving the same mail multiple times. I can't figure out what's happening:

  • When redirecting the emails to log, I see exactly one mail for each user as expected;
  • Every other events trigger emails to be sent to a single user. However, no one has received multiple emails from these events.

The app is using Sendinblue as an external SMTP service. Some hints I got:

  • The hourly mail quota was very low -> the email were received 3 times (and the queue on Sendinblue was immediately filled)
  • The hourly mail quota was raised 10x -> no more queues on Sendinblue, but now users are receiving the same email up to 7 times!

Solution

  • 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!