Laravel

Using the MessageSending Event in Laravel

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.

1// get all of the recipients of the message and merge into a single array
2$recipients = array_merge(
3 $event->message->getTo() ?: [],
4 $event->message->getCc() ?: [],
5 $event->message->getBcc() ?: []
6);
7
8// if the desired email doesn't exist in the recipients array
9// use the addBcc method to add it
10if(!array_key_exists('hello@example.com', $recipients))
11{
12 $event->message->addBcc('hello@example.com', 'My App');
13}
14
15// return the message object
16return $event->message;

Using the Event

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.

Code highlighting provided by Torchlight