Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

A better way to send emails or not send emails based on the environment?

Hello,

We have 3 environments: local development, test server and the prod.

  • The local dev server cannot send emails.

  • The test can send emails but I want to set the email addresses manually and not to the actual recipients.

  • The prod should send emails to the actual recipients.

What I do right now is I have this function in each controller:

public function sendEmails($mailObject, $recipients)
{
    $environment= config('app.env');

    switch ($environment) {
        case 'local':
            Log::debug('Email sent');
            break;
        case 'test':
            Mail::to('[email protected]')->send($mailObject);
            break;
        case 'production':
             Mail::to($recipients)->send($mailObject);
            break;
    }
}

And the usage would be for example:

$mailObject = new \App\Mail\SomeMail();
$this->sendEmail($mailObject, $user->email);

The first thing I can do to improve it is to move this function to a Trait perhaps instead of having that in every Controller. But besides that - is there a better way to do that? Maybe there's already a built-in feature in Laravel for that?

Thanks

0 likes
5 replies
Ligonsker's avatar

@Tray2 Thank you. In case we can't use 3rd party stuff like Mailtrap, and I have to use locally available things (such as what I currently do, and the internal SMTP server) - should I just leave it as it is right now, and move this function to a Trait?

The only downside to that is, that I add another line of code (the call for sendEmail(...) instead of directly using Mail::to..)

Update: Oh wait, I didn't read all the way through, I think the link you sent has other options, i.e. this part:

    if ($this->app->environment('local')) {
        Mail::alwaysTo('[email protected]');
    }

I will try !

martinbean's avatar

@ligonsker Don‘t add conditional code like that. Determining how emails are sent is what the MAIL_DRIVER environment variable is for. You set its value per environment to change how your application behaves without having to write loads of if statements or switch statements like you’re doing.

So, use something like Mailpit in non-production environments. It’s self-hosted and not a third-party service. But again, you don’t want to be littering your app with if and switch statements; use configuration to actually configure your application instead.

Please or to participate in this conversation.