Force Laravel to always send email to a dummy email address

Use this handy Laravel feature to ensure that all email is routed to a single email address.

Mike Griffiths

We've all been there... well maybe not, but it is easy done... you're developing a command locally to batch send some emails and forgot that you recently pulled the production database. The next minute you're pumping out thousands of emails to customers of a half-baked feature you've just started.

There are plenty of ways to prevent this happening. Personally, I use MailTrap in my local environments, but there are plenty of occasions where your mail settings in your environment may be live, or perhaps you want to prevent your staging, dev or QA environments from sending mail (or always send it to the same address).

Well, you're in luck.

The Mail facade has a great feature/method called alwaysTo which allows you to always send mail to a specific email address.

Mail::alwaysTo('[email protected]');

You can easily run this code in your AppServiceProvider and wrap it in an environment check to ensure it doesn't run on production.

<?php
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    // [...]
    public function boot()
    {
        // Ensure it only runs in prod
        
        if (! app()->environment('production')) {
            Mail::alwaysTo('[email protected]');
        }
    }
}

You can read a bit more about this method in the Laravel API docs.

Don't forget the other always methods too:

And there's also this one, which even strips CC and BCCs:

Mail::setGlobalToAndRemoveCcAndBcc(Message $message);

Be aware that this one expects a $message though, not an address, so it's somewhat different.