• Reading time ~ 1 min
  • 20.09.2022

There's an (as of yet) undocumented way in Laravel to prevent it from sending emails to any old address.

Why is this useful? Well, some of us aren't perfect 😅. Sometimes we accidentally send thousands of emails to real customers from our staging environment or even in our tests.

There are lots of ways to avoid this, but Laravel has a nice, easy method out of the box!

# File app/Providers/AppServiceProvider.php
 
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\ServiceProvider;
 
class AppServiceProvider extends ServiceProvider
{
    // Stuff omitted
 
    public function boot()
    {
        f (! app()->environment('production')) {
            Mail::alwaysTo('[email protected]');
        }
    }
}

What's Happening with alwaysTo?

The handy alwaysTo() method will over-ride all addresses added in the to, cc, and bcc within an email message.

This is done within the Illuminate\Mail\Mailer class (see here). Note the code comment:

// If a global "to" address has been set, we will set that address on the mail
// message. This is primarily useful during local development in which each
// message should be delivered into a single mail address for inspection.
if (isset($this->to['address'])) {
    $this->setGlobalToAndRemoveCcAndBcc($message);
}

So, in our code up above, we tell Laravel to only send emails to [email protected] if we are NOT in the production environment!

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297