Override Yii2 Swiftmailer Recipient

后端 未结 1 1600
攒了一身酷
攒了一身酷 2021-01-25 20:54

I need to override the recipient email for every instance of Swiftmailer\'s send() function throughout my Yii2 application. This is for the purpose of load testing.

相关标签:
1条回答
  • 2021-01-25 21:34

    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.

    0 讨论(0)
提交回复
热议问题