SwiftMailer 像 PHPMailer 一样强制 SMTPAuth

我正在努力使用 Exchange 在线帐户从网络发送邮件。最近,在迁移到 Laravel 时,我发现与 PHPMailer 配合良好的现有设置不适用于基于 SwiftMailer 的 Laravel。


PHPMailer 的工作原理:


$data = new PHPMailer(true);

$data->CharSet = 'UTF-8';

$data->isSMTP();

$data->Host = config('mail.host');

$data->SMTPAuth = true;          // apparently this line does the trick

$data->Username = config('mail.username');

$data->Password = config('mail.password');

$data->SMTPSecure = config('mail.encryption');

$data->Port = config('mail.port');

$data->setFrom('site@mydomain.com','site mailer');

$data->addAddress('me@mydomain.com', 'Me');

$data->Subject = 'Wonderful Subject PHPMailer';

$data->Body = 'Here is the message itself PHPMailer';

$data->send();


与 SwiftMailer 相同的逻辑:


$transport = (new Swift_SmtpTransport(config('mail.host'), config("mail.port"), config('mail.encryption')))

    ->setUsername(config('mail.username'))

    ->setPassword(config('mail.password'));

$mailer = new Swift_Mailer($transport);

$message = (new Swift_Message('Wonderful Subject'))

  ->setFrom(['site@mydomain.com'=>'site mailer'])

  ->setTo(['me@mydomain.com'=>'Me'])

  ->setBody('Here is the message itself');

$numSent = $mailer->send($message);

SwiftMailer,给出错误:


530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [xxxxxxxxxxxxx.xxxxxxxx.prod.outlook.com]

两种情况下的 SMTP 服务器smtp-mail.outlook.com和端口 587 相同


NB是的,我很清楚其他地方使用的建议mydomain-com.mail.protection.outlook.com和端口 25。但是这样做后,垃圾邮件中会收到消息,原因是“我们无法验证发件人的身份”,这是我无法接受的行为。


我们谈论的是少量,所以对其他/第 3 方群发邮件服务不感兴趣。


到目前为止,我的发现是,这$phpMailer->SMTPAuth = true;改变了游戏规则。如果没有这一行,它会产生与 SwiftMailer 相同的错误。 问题是如何强制执行相同的行为SwiftMailer?


如前所述,我实际上使用了 Laravel 邮件,但为了这个示例的目的,我直接提取了 SwiftMailer 调用。


编辑: SwiftMailer 有$transport->setAuthMode(),它应该与$phpMailer->AuthType. 为两者尝试了可用的 CRAM-MD5、LOGIN、PLAIN、XOAUTH2 值。PHPMailer 与所有这些一起工作,除了 XOAUTH2。对于 SwiftMailer,这些都没有改变任何东西,仍然给出错误。


EDIT2:我确实有 SPF 记录(DNS TXT)v=spf1 include:spf.protection.outlook.com -all


已解决:添加tls到 Swift 运输结构中。显然PHPMailer的默认设置为TLS,因为config('mail.encryption')是null。


宝慕林4294392
浏览 206回答 1
1回答

一只萌萌小番薯

处理用 Java 发送邮件,但这里的基本问题似乎是一样的:如果您通过端口 587 连接,您最初会启动一个普通连接,您必须通过显式发送 STARTTLS 命令来启动 TLS。您必须告诉 JavaMail 这样做,否则它会尝试在不安全的情况下进行。除非建立 TLS 连接,否则 SMTP 服务器不会发送任何身份验证机制信息,因此 JavaMail 假设不需要身份验证并尝试在没有身份验证的情况下发送邮件。因此,您似乎需要在此处明确指定您希望它也成为加密连接。Swift_SmtpTransport 构造函数的第三个参数执行此操作,提供“ssl”或“tls”:new Swift_SmtpTransport('smtp.example.org', 587, 'ssl'); // or new Swift_SmtpTransport('smtp.example.org', 587, 'tls');使用 phpMailer 版本,您需要 $data->SMTPSecure 来处理那部分。
打开App,查看更多内容
随时随地看视频慕课网APP