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

  • laravel bulk imports

    Small note, mostly for myself, as a reminder that when doing large imports of data, you may not need each block to be processed as an Eloquent model. That code above would generally be faster as Obviously there are even faster ways – preparing your data in some text format, and using your DB cli…

  • MySQL speed boost

    I hit a problem the other day with concurrent queries causing deadlocks.  Using innodb gives you a lot of protection with respect to transaction support, but it carries a moderate amount of overhead, and unless you’re aware of what’s going on, you may be paying a higher price which can eventually cause performance or deadlock…

  • CyclopsMonitor

    I’ve been posting more about this new service over on linkedin, but haven’t posted much here. CyclopsMonitor is a web monitoring service – checking if a web address is up, how fast it responds, if specific content is available, when SSL/TLS certs expire, when domain name expires, and… sending you notifications when problems occur. Currently,…

Leave a Reply

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