Override Yii2 Swiftmailer Recipient

北战南征 提交于 2019-12-02 07:36:01

If this is for test only why not set useFileTransport so emails will be saved in the folder of your choice instead of being sent. To do so configure it like this:

'components' => [
    // ...
    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'useFileTransport' => true,
    ],
],

This will save all emails in the @runtime/mail folder, If you want different one set:

'mailer' => [
    // ...
    'fileTransportPath' => '@runtime/mail', // path or alias here
],

If you want to still send emails and override recipients you can for example extend yii\swiftmailer\Mailer class.

class MyMailer extends \yii\swiftmailer\Mailer
{
    public $testmode = false;
    public $testemail = 'test@test.com';

    public function beforeSend($message)
    {
        if (parent::beforeSend($message)) {
            if ($this->testmode) {
                $message->setTo($this->testemail);
            }
            return true;
        }
        return false;
    }
}

Configure it:

'components' => [
    // ...
    'mailer' => [
        'class' => 'namespace\of\your\class\MyMailer',
        // the rest is the same like in your normal config
    ],
],

And you can use it in the same way you use mailer component all the time. When it's time to switch to test mode modify the configuration:

'mailer' => [
    'class' => 'namespace\of\your\class\MyMailer',
    'testmode' => true,
    'testemail' => 'test222@test.com', // optional if you want to send all to address different than default test@test.com
    // the rest is the same like in your normal config
],

With this, every email will be overridden with your recipient address.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!