founders's avatar

How to use event "Illuminate\Mail\Events\MessageSending" to replace $to according to environment

Hello,

I am trying to use "Illuminate\Mail\Events\MessageSending" event to replace who the email is sent to depending on the server environment. I have a couple forms, sending emails to a couple of people depending on the subject. I'm trying to figure out a way to tell Mail class this:

If it's production environment, go ahead and send the emails, otherwise, send them only to [email protected].

However, the "MessageSending" event only returns allows me to change $message, not $to.

What should I do?

0 likes
5 replies
morteza's avatar

You can use getEnv('APP_ENV') to check your environment, but it seems it's best use case for mailtrap

founders's avatar

The problem isn't knowing the environment, is to change $to and return it to Mail :|

founders's avatar

I found out. You don't need an Event listener do to this...

  1. Open config/mail.php

  2. Store the whole array in a variable. Example:

return [
    // mail config
]

Becomes

$config = [
    // mail config
]
return $config
  1. Then, before the return, add this:
if (env('APP_ENV') !== "production") {
    $config['to'] = [
        'address' => '[email protected]',
        'name' => 'Developer'
    ];
}
vbarseghian's avatar

Not actually sure, what's the issue, but what you can do here is to create event listener like so and add it in EventServiceProvider

        'Illuminate\Mail\Events\MessageSending' => [
            'App\Listeners\CheckReceiverBoforeSend',
        ],

Then In actual Listener class, you will have few lines of code

<?php

namespace App\Listeners;

use Illuminate\Mail\Events\MessageSending;

class CheckReceiverBoforeSend
{
    public function handle( MessageSending $event )
    {
        if(config('app.env') !== 'production'){
            $event->message->setTo(['emailAddress1', 'emailAddress2']);
        }
    }
}

That's all

Please or to participate in this conversation.