Send emails to a single test email address for test environments in Laravel
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.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.