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.

// get all of the recipients of the message and merge into a single array
$recipients = array_merge(
    $event->message->getTo() ?: [],
    $event->message->getCc() ?: [],
    $event->message->getBcc() ?: []
);
// if the desired email doesn't exist in the recipients array
// use the addBcc method to add it
if(!array_key_exists('[email protected]', $recipients))
{
	$event->message->addBcc('[email protected]', 'My App');
}
// return the message object
return $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.