- Published on
Add BCC to all outgoing emails from your Laravel application
- Authors
- Name
- Saleem Hadad
- @saleemhadad
Sometimes it's very helpful to debug all your outgoing emails -or part of them- from your Laravel app, especially in the early stage of the product's release 1.
By default, Laravel fires two events every time an email is about to send MessageSending and when it sent MessageSent and that works both for normal mailables and mail notifications.
You may register an event listener (let's call it MessageSendingListener
) for this events in your EventServiceProvider
as follow:
<?php
namespace App\Providers;
use App\Listeners\MessageSendingListener;
use Illuminate\Mail\Events\MessageSending;
// ..
class EventServiceProvider extends ServiceProvider
{
// ..
protected $listen = [
MessageSending::class => [
MessageSendingListener::class
],
];
// ...
}
Now, create the listener by running:
php artisan make:listener MessageSendingListener
Then, add the following code to your listener:
<?php
namespace App\Listeners;
use Illuminate\Mail\Events\MessageSending;
class MessageSendingListener
{
public function handle(MessageSending $event)
{
if(! env("DEBUG_EMAILS")) { return; }
$event->message->addBcc('youremail@example.com'); // you can pass an array as well
}
}
If you notice, I added the env check DEBUG_EMAILS
to make it easier to stop/resume debugging outgoings emails.
To activate sending BCC emails, just add the following key to your .env
file.
DEBUG_EMAILS=true
Footnotes
Please note this method is good only if you have a small number of outgoing emails. NEVER run this on a large scale or in a production environment since most providers (such as AWS) charges you for sending emails to BCC users as a separate email for each recipient. ↩