在 symfony 中使用带有 swiftmailer 的 office365 服务器发送电子邮件

Sending email using office365 server with swiftmailer in symfony

我正在尝试在 symfony 中使用 swiftmailer 和 office365 服务器注册后发送一封确认电子邮件。我已经尝试了我遇到的所有主机、端口和加密类型的组合。

目前我的 .env 文件包含这一行:

MAILER_URL=smtp://smtp.office365.com:587?encryption=ssl&auth_mode=login&username="myusername@mycompany.com"&password="mypassword"

*注意:我使用“”作为我的用户名和密码,因为它们包含特殊字符,而且我在某处读到这可能会导致 MAILER_URL.

出现问题

我的 swiftmailer.yaml 文件包含:

swiftmailer:
    url: '%env(MAILER_URL)%'
    stream-options:
        ssl:
            allow_self_signed : true
            verify_peer: false

最后,我将在我的控制器中使用此代码发送我的电子邮件:

 $message = (new \Swift_Message('Referral tool registration'))
            ->setFrom('myusername@mycompany.com')
            ->setTo('test@gmail.com')
            ->setBody(
                $this->renderView(
                    'email/notification/user_registered.html.twig',
                    ['firstName' => $user->getFirstName(),
                     'lastName' => $user->getLastName()
                    ]
                    ),
                'text/html'
            );

 $mailer->send($message);

根据当前选择的主机、端口和加密,我得到:"Connection could not be established with host smtp.office365.com [ #0]"

更新: 当我输入 telnet smtp.office365.com 587 我得到一个有效的响应,所以我想问题与网络无关,端口没有被阻塞.

试试这个:

MAILER_URL=smtp://smtp.office365.com:587?encryption=tls&username="myusername@mycompany.com"&password="mypassword"

您必须使用 encryption=tls,对您的 USER_NAME 和 PASSWORD 进行 urlencode,并且您不应像以前那样将 USER_NAME 和 PASSWORD 括在引号中。

让我们假定这些凭据并对它们进行 urlencode:

USERNAME = `email@domain.tld` → `email%40domain.tld`
PASSWORD = `pa$$w#rd` → `pa%24%24w%23rd`

使用上述凭证的正确配置将如下所示:

MAILER_URL=smtp://smtp.office365.com:587?encryption=tls&auth_mode=login&username=email%40domain.tld&password=pa%24%24w%23rd

Symfony 4 使用 Mailer Component,如果你熟悉那么你可以使用如下的环境变量

# Office 365 Outlook
MAILER_DSN=smtp://support@company.com:password@smtp.office365.com:587

AND config/packages/mailer.yml

framework:
    mailer:
        dsn: '%env(MAILER_DSN)%'

预装的唯一传输方式是 SMTP。不需要任何其他传输包,不像 google-mailer 或 amazon-mailer..

对我有用。

我也遇到过类似的问题,我通过登录账号修改密码解决了

我的情况 - 帐户是新帐户,登录后的第一个屏幕是要输入的字段:当前密码、新密码、重复密码。

我的环境:

MAILER_DSN=smtp://support@company.com:password@smtp.office365.com:587