【发布时间】:2019-09-17 07:39:18
【问题描述】:
我在我的 Symfony 3.4 项目中使用 Swiftmailer。 我编写了以下组件来发送邮件:
class MailSender {
private $mailer;
public function __construct(\Swift_Mailer $mailer) {
$this->mailer = $mailer;
}
public function sendMail($target, $subject, $content) {
$message = (new \Swift_Message($subject))
->setFrom('***@gmail.com')
->setTo($target)
->setBody($content, 'text/html');
return $this->mailer->send($message);
}
}
在我的 services.yml 中我添加了:
AppBundle\Service\MailSender:
arguments:
$mailer: '@swiftmailer.mailer'
在我的parameters.yml中我添加了:
parameters:
mailer_transport: smtp
mailer_host: smtp.gmail.com
mailer_user: ***@gmail.com
mailer_password: ***
如果我现在使用 php/bin 控制台服务器启动我的服务器:运行并执行 sendMail 方法,不幸的是邮件没有被发送(尽管邮件程序返回 1 作为响应)。 Symfony Profiler 显示以下错误日志: 刷新电子邮件队列时发生异常:预期响应代码为 250,但得到代码“530”,消息为“530 5.7.0 必须先发出 STARTTLS 命令。g185sm18205331wmf.30 - gsmtp”
罕见的是:如果我在我的 TestCase 中自己构造 \Swift_Mailer 对象,邮件确实会被发送。
public function testSendMail() {
// GIVEN
$transport = (new \Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
->setUsername('***@gmail.com')
->setPassword('***');
$swiftMailer = new \Swift_Mailer($transport);
$mailSender = new MailSender($swiftMailer);
// WHEN
$mailsSent = $mailSender->sendMail('***@t-online.de', 'testMail', 'The Mailsender works!');
// THEN
$this->assertEquals($mailsSent, 1);
}
如果我将 \Swift_Mailer 作为服务注入,谁能明白为什么它不起作用?
【问题讨论】:
-
您是否允许您的应用程序出现在 GMAIL 中?只要不允许,GMAIL 就会阻止您的应用程序发送任何邮件。
-
您好 Preciel,您是指启用不太安全的应用程序吗?因为是的,它已经启用。不过感谢您的提示!
-
不确定是不是这样,但是当您尝试使用您的应用发送电子邮件时,Google 应该已经向您发送电子邮件,告诉您该应用已被阻止,您应该使用 API 密钥等
标签: symfony swiftmailer symfony-3.4