2016-11-10 72 views
0

我需要重寫我的整個Yii2申請Swiftmailer的send()功能的每個實例的收件人的電子郵件。這是爲了進行負載測試。覆蓋Yii2 Swiftmailer收件人

是否有一個簡單的方法來做到這一點?或者至少有一種方法來做到這一點,而無需編輯Swiftmailer的供應商文件?

回答

1

如果這是僅用於測試,爲什麼不設置useFileTransport這樣的電子郵件將被保存在您選擇的文件夾中,而不是被髮送。要做到這一點這樣的配置是:

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

這將保存所有的電子郵件在@runtime/mail文件夾,如果你想不同的一組:

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

如果你想還是發送電子郵件,並覆蓋收件人你可以例如延長yii\swiftmailer\Mailer班。

class MyMailer extends \yii\swiftmailer\Mailer 
{ 
    public $testmode = false; 
    public $testemail = '[email protected]'; 

    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組件所有的時間以同樣的方式使用它。當是切換到測試模式的時候修改配置:

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

這樣,每封電子郵件都會被您的收件人地址覆蓋。

+0

真棒!這樣一個完整的答案!謝謝!! – LXXIII