使用 Yii2 扩展使用 swiftmailer 发送电子邮件


Sending email with swiftmailer using the Yii2 extension

我正在做一个项目,我想测试发送给用户的电子邮件,但到目前为止,我没有运气设置它。我正在使用Codeception并在Vagrant中运行它。我现在要做的是:

return 'Yii::$app->mailer->compose()
->setFrom($from)
->setTo($to)
->setSubject('Welcome')
->send();

我有一个主本地.php,看起来像这样:

'mailer'=> ['class' => 'yii'swiftmailer'Mailer',
'viewPath' => '@common/mail',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'localhost',
'port' => 1025,
'useFileTransport' => false,
],

起初我省略了'useFileTransport' => false,然后我在"运输"之前添加了它,并尝试将其移动到"运输"中,正如您现在所看到的,但它是一样的。文件/电子邮件在项目中创建为 .eml 文件,但不发送邮件。我尝试设置mailcatcher(http://mailcatcher.me/),并且实际上已经工作了,但是如果我可以在配置中进行更改,而不是使用不同的方法和更改代码,那么邮件将发送到我想要的地方,那就太好了。(我也尝试使用端口 1080,所以不是这样。

任何帮助将不胜感激。如果您需要更多信息,请告诉我!

更新:我发现我得到了一个不同的配置文件,我实际上可以使用'useFileTransport' => false,然后它不会在项目中创建文件/电子邮件,但仍然不发送。我将从main-local.php显示的设置复制到此配置文件中,在"传输"之前'useFileTransport' => false上移,但我仍在寻找发送这些电子邮件的方法

$useFileTransport是yii'swiftmailer'Mailer类的属性,因此它不属于transport部分。

如果您的邮件程序配置如下,它将尝试通过 SMTP 将邮件传递到端口 1025 上的本地主机上运行的邮件服务器:

'mailer'=> [
    'class' => 'yii'swiftmailer'Mailer',
    'viewPath' => '@common/mail',
    'useFileTransport' => false,
    'transport' => [
         'class' => 'Swift_SmtpTransport',
         'host' => 'localhost',
         'port' => 1025,
    ],
],

这对我来说听起来有些不寻常,因为SMTP的默认端口是25

确保 SMTP 服务器实际在该端口上运行。例如,通过使用 telnet 命令:

telnet localhost 1025

这应该给你这样的东西:

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 your.servername ESMTP Postfix

通过键入 quit 退出 SMTP 会话,然后按回车键。

您也可以检查通常位于 /var/log/mail.log 的邮件服务器日志文件。您可以使用 查看正在记录的消息

tail -f /var/log/mail.log

当您尝试发送它们时。

花了

我几天时间,但终于找到了问题所在!

所以问题是我在更新部分中提到的另一个配置。隐藏在codeception/config/config.php缺少一行

'mailer' => [
        'class' => 'yii'swiftmailer'Mailer',
        'viewPath' => '@common/mail',
        //For email creation in project
        //'useFileTransport' => true,
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'localhost',
            'port' => 1025,
            'encryption' => '',
        ],
    ],

我所需要的只是加密,它只需要是空的。电子邮件现在正在按预期方式发送,并且看起来不错!

希望这对那里的某人有所帮助,测试愉快!