s-ichikawa/laravel-sendgrid-driver

Uses wrong mailer when mailer set on the fly

mukarramkhalid opened this issue · 0 comments

What version of PHP and Laravel are you using?

PHP 8.1.13
Laravel Framework 9.47.0

What did you do?

Starting Laravel version 7, we can change the mailer on the fly. Something like:

Mail::mailer('sendgrid')
        ->to($user->email)
        ->send(new InvoiceMail());

This would set the mailer for this mail only to SendGrid even if the mailer in config or env is set to something else.
In that case, the following method returns the wrong mailer, which creates problems.

/**
* @return string
*/
private function mailDriver()
{
return function_exists('config') ? config('mail.default', config('mail.driver')) : env('MAIL_MAILER', env('MAIL_DRIVER'));
}

What did you expect to see?

I expected the mailer to use sendgrid, which was set on the fly, instead of the one set in config or env.

What did you see instead?

The mailer from the config or env was used instead of sendgrid which was set on the fly.

How to Fix

You can always get the current mailer with $this->mailer within the Mailable class. So something like the following may fix the problem without losing the backward compatibility.

    /**
     * @return string
     */
    private function mailDriver()
    {
        if (!empty($this->mailer)) {
            return $this->mailer;
        }
        if (function_exists('config')) {
            return config('mail.default', config('mail.driver'));
        }
        return env('MAIL_MAILER', env('MAIL_DRIVER'));
    }