Using the MessageSending event in Laravel

Joe Dixon
dotdev
Published in
2 min readMay 29, 2017

--

Like all core Laravel features, sending mail is made easy and convenient by the clean and expressive API that it exposes.

Carrying out tasks such as changing service providers from Mandrill to Mailgun (when they decide to only make it available to Mailchimp customers) can be handled with a simple 5 second config change. Trapping mail in development and staging whilst sending in production is handled by an environment variable. It really does take the pain out of email.

Recently, I came across the need to bcc a mailbox into every email sent from my app. I needed to do this only when the email wasn’t already being sent to that mailbox. Searching the docs for a solution, I came across the MessageSending event.

Taking a deeper dive into this event, I found that Laravel provides access to the whole message object immediately prior to sending. This made my job nice and simple.

All I had to do was merge all of the recipients of the array together and check whether or not my desired bcc address already existed in that array. If not, I could simply use the addBcc method to add it before returning the modified message object.

This isn’t the only use case for this event. It can be used for anything from logging message sends to adding additional headers to outgoing messages or even asking for a read receipt.

I hope you enjoyed reading this. If you have any questions or comments, drop me a message

Originally published at joedixon.co.uk.

--

--

Founder and CTO of @ubisend. Creator of @getjukebot. Father and Husband. Big sport and technology enthusiast.