【问题标题】:How to fix swiftmailer configuration in Symfony 3.4 project如何修复 Symfony 3.4 项目中的 swiftmailer 配置
【发布时间】: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


【解决方案1】:

您是否从 symfony 文档中尝试过这个? How to Use Gmail to Send Emails

# app/config/parameters.yml
parameters:
    # ...
    mailer_transport: gmail
    mailer_user:     your_gmail_username
    mailer_password: your_gmail_password
# app/config/config_dev.yml
swiftmailer:
    transport: '%mailer_transport%'
    username:  '%mailer_user%'
    password:  '%mailer_password%'

请注意,您应该将 mailer_transport 设置为 gmail 而不是 smtp

【讨论】:

  • 是的,这是正确的解决方案,我已经在 parameters.yml 中进行了配置,但我还必须将其添加到 config_dev.yml 中。我有点惊讶,我认为将它放在一个地方就足够了。千百次感谢您的提示!
  • 啊,我读到过,在 parameters.yml 中也可以将 smtp 更改为 gmail。所以这样做可能就足够了。
猜你喜欢
  • 2018-11-25
  • 2019-11-02
  • 2019-01-26
  • 2019-02-21
  • 2013-05-04
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
相关资源
最近更新 更多