Skip to content

Laravel’s alwaysTo() — Avoid Accidental Email Sending

avoid accidental email sending with alwaysTo method

In this post, we’re going to have a look at a simple way of preventing sending e-mails to real customers from our local or staging environment with the help of alwaysTo() method.

Let’s picture the following scenario:

We’re developing a new feature in our local environment and in the database we have real customer data.

Because of this, we wouldn’t want to send e-mails to real customers while developing or testing the new feature.

There are several ways we can avoid this.

Instead of sending the e-mails, we:

  • can write them into our log files using the log mail driver
  • may use a service like HELO, MailTrap or MailHog

But in this post, we’re going to be focused on using the alwaysTo() method by the Mail facade.

Let’s get started!

Implementing alwaysTo()

For the sake of this example, I’m going to make use of the boot() method of the AppServiceProvider class to invoke the alwaysTo() method offered by the Mail facade.

Obviously, you’ll have to adapt your code according to your needs, but this should get you started.

Inside the boot() method we want to check if the app environment is NOT production, meaning it may be local, staging, or any other environment the app may have,

From now on, all the e-mails will be sent to your e-mail instead of being sent to a real customer.

What’s with this method?

If you’re curious to navigate to the source code of the alwaysTo() method you will notice that you cannot do that because it is not documented yet.

I don’t know the reason why it is not documented yet, but I did some digging and found that this method was introduced in Laravel 5.1.

However, it only appears in the official documentation starting with Laravel 8.

How does alwaysTo() work?

In the absence of comprehensive documentation, I suggest we look at the source code to better understand what this method does.

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

I hope you now have a clearer view of how you can avoid accidentally sending e-mails to real users or customers when your app is running on a local or staging environment.

Let me know what you think about this article in the comments section below.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.