覆盖 Yii2 Swiftmailer 收件人 [英] Override Yii2 Swiftmailer Recipient

查看:29
本文介绍了覆盖 Yii2 Swiftmailer 收件人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为整个 Yii2 应用程序中 Swiftmailer 的 send() 函数的每个实例覆盖收件人电子邮件.这是为了负载测试.

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.

有没有简单的方法可以做到这一点?或者至少有一种方法可以在不编辑 Swiftmailer 的供应商文件的情况下做到这一点?

Is there an easy way to do this? Or at least a way to do it without editing Swiftmailer's vendor files?

推荐答案

如果这只是为了测试为什么不设置 useFileTransport 以便电子邮件将保存在您选择的文件夹中而不是发送.为此,请像这样配置它:

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,
    ],
],

这会将所有电子邮件保存在 @runtime/mail 文件夹中,如果您想要不同的一组:

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

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

如果您仍然想发送电子邮件并覆盖收件人,您可以例如扩展 yii\swiftmailer\Mailer 类.

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;
    }
}

配置:

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

而且你可以像使用 mailer 组件一样使用它.当需要切换到测试模式时修改配置:

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.

这篇关于覆盖 Yii2 Swiftmailer 收件人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆