Override subject for email sent with universal "to"

Re: Mail Configuration - October CMS - 3.x

Is there a way to override the mail subject (for all mail sent out), to prefix it with:

[{APP_ENV} + {Actual ‘To’ Address}]

only when the universal ‘to’ is being used (for non-prod development, ie APP_ENV !== prod) ?

Maybe this? Mail - Laravel 9.x - The PHP Framework For Web Artisans

Using A Global to Address
Finally, you may specify a global “to” address by invoking the alwaysTo method offered by the Mail facade. Typically, this method should be called from the boot method of one of your application’s service providers:

use Illuminate\Support\Facades\Mail;
 
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    if ($this->app->environment('local')) {
        Mail::alwaysTo('taylor@example.com');
    }
}

Hi @apinard thanks but trying to override the subject of all outgoing mail, not the global ‘to’ address (this is already achieved with ‘to’ => […] in the config/mail.php

Similar to this basically: https://laracasts.com/discuss/channels/laravel/mailer-change-to-and-subject-before-sending

i had this example before and removed it, because it is lil bit offtopic.
@trader47 check all events and bind beforeSend where you can change or
on

Mail::send('template', $vars, function ($message) {
  $this->app->environment('local') {
    $message->subject('[' . $this->app->environment .' - '. $toEmailAddress .']');
  }
});

or you can implement notifiable trait and whole logic insert into custom class

Just reread the topic and it does says the subject! I don’t know why I assumed the “To” haha

Thanks @snipi

Got it working by putting this in plugin’s boot() fxn:

Event::listen(MessageSending::class, function (MessageSending $message) {
            if (!$this->app->environment('prod')) {
                $addresses = $message->message->getTo();

                if (count($addresses) > 0) {
                    $toEmail = $addresses[0]->getAddress();
                    $message->message->subject(
                        sprintf('[%s: %s] %s', $this->app->environment(),
                            $toEmail,
                            $message->message->getSubject()
                        )
                    );
                }
            }
        });

This will have to do until one day can get MailHog working! :joy:

1 Like