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.
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.