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);
If you run the above code, the system will send an email to firstname.lastname@example.org. The system will then send a second email with to both email@example.com *and* firstname.lastname@example.org. 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.
- 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.
- You can also just create a new mailable each time.
I help this helps someone 🙂