Send emails to a single test email address for test environments in Laravel

Amit Merchant · April 23, 2022 ·

When you’re working on a Laravel application, chances are you might be working with a lot of emails. For instance, every time, a new user is created, a welcome email and a confirmation email will be sent to the user.

There would be many such instances where emails will be fired. So, in your test environments, it doesn’t make sense to use different emails for various purposes.

What if we could just use a single email address and all the emails of the application would be sent to this email address? Well, today, I learned about how you would do this through this tweet.

The Mail::alwaysTo() method

There exists this alwaysTo() method in the Mail facade where you can specify a global to address to which all the emails of the application would be sent.

You can configure this in the boot method of your application’s AppServiceProvider like so.

use Illuminate\Support\Facades\Mail;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        if (!app()->isProduction()) {
            Mail::alwaysTo('[email protected]');
        }
    }
}

As you can tell, we can set this up for all the environments which are not production and we are good!

A universal recipient in the config

The other way that you can do this is by setting up a universal recipient by specifying the to option in the config/mail.php file like so.

'to' => [
    'address' => env('MAIL_TEST_EMAIL_ADDRESS', '[email protected]'),
    'name' => env('MAIL_TEST_NAME', 'Test User')
]

Now, all the email from the application will be sent to the email configured here.

Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?