Laravel is sending duplicate emails!

So… I wrote a previous post about how to prevent duplicates, but this post is about a different type of duplication problem. I encountered this issue about 18 months ago, and asked around, and few people seemed to know what I was talking about, and I don’t specifically see it mentioned in the docs. So.. here goes.

// Laravel 5.7 and above, IIRC
// haven't checked on older versions
$mailable = new MyMailableClass($data);
Mail::to("s@kimsal.com")->send($mailable);
Mail::to("j@kimsal.com")->send($mailable);

If you run the above code, the system will send an email to s@kimsal.com. The system will then send a second email with to both j@kimsal.com *and* s@kimsal.com. Why?

Behind the facade, the $mailable class has a ‘to’ list of recipients, and every call to Mail::to will *add* to the mailable’s recipient list, not clear and start over. This is certainly not intuitive, and is likely the root cause of a lot of the posts I’ve seen about “duplicate email” behavior. Certainly there can be other causes, but I’ve hit this one personally, and know it was a bugger to figure out.

The fix? I only know of two fixes.

  1. If you’re really sending the exact same thing to multiple addresses, you can send to one array of addresses. The downside is that each person will see the other recipients’ addresses. In some cases, this won’t matter. In others, it may be a big privacy issue.
  2. You can also just create a new mailable each time.

I help this helps someone

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *