使用PHPMailer通过Outlook发邮件遇认证失败错误求解决
使用PHPMailer通过Outlook沙箱邮箱发送邮件时遭遇SMTP认证失败
错误信息
Message could not be sent. Mailer Error: "The following From address failed: xxxxx@xxxxx.onmicrosoft.com : MAIL FROM command failed,Client not authenticated to send mail. [ xxxxxx.namprd13.prod.outlook.com 2023-07-14T21:47:08.967Z 08DB842E797B0C23]\r\n,530,5.7.57SMTP server error: MAIL FROM command failed Detail: Client not authenticated to send mail. [xxxx.namprd13.prod.outlook.com 2023-07-14T21:47:08.967Z 08DB842E797B0C23]\r\n SMTP code: 530 Additional SMTP info: 5.7.57SMTP server error: MAIL FROM command failed Detail: Client not authenticated to send mail. [xxxxxx.namprd13.prod.outlook.com 2023-07-14T21:47:08.967Z 08DB842E797B0C23]\r\n SMTP code: 530 Additional SMTP info: 5.7.57"
背景说明
使用Outlook沙箱邮箱,此前通过ms-graph-sdk可正常发送邮件,推测邮箱本身无问题,但用PHPMailer时持续触发认证失败报错。
现有代码
try { //Server settings $mail->SMTPDebug = SMTP::DEBUG_SERVER; $mail->Host = 'smtp-mail.outlook.com'; //smtp.office365.com:587 $mail->Username = 'xxxx@xxxx.onmicrosoft.com'; $mail->Password = 'xxxxxxxxxx'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; $mail->isSMTP(); //$mail->SMTPAuth = true; //Recipients $mail->setFrom('xxxx@xxxxxxx.onmicrosoft.com', 'Mailer'); $mail->addAddress('myaddress@gmail.com'); //Content $mail->isHTML(true); $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body <b>in bold!</b>'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if (! $response = $mail->send()) { Log::info('Message could not be sent.'); Log::info('Mailer Error: ' . json_encode($mail->ErrorInfo)); exit; } else { echo 'Message of Send email using Outlook SMTP server has been sent'; } echo 'Message has been sent'; } catch (Exception $e) { Log::info("Message could not be sent. Mailer Error:" . json_encode($mail->ErrorInfo)); }
已尝试但无效的方案
- 在Outlook账户设置中开启“允许不安全应用访问”
- 启用邮箱的POP3/IMAP协议
- 确认SMTP服务器地址、端口及加密方式设置正确
解决方案
1. 强制开启SMTP认证
代码中$mail->SMTPAuth = true;被注释,而Outlook SMTP服务器要求必须认证,取消注释该行:
$mail->SMTPAuth = true;
2. 保证发件地址与认证账户一致
setFrom中的邮箱地址必须和Username完全匹配,否则会触发认证失败,修正为:
$mail->setFrom('xxxx@xxxx.onmicrosoft.com', 'Mailer');
3. 更换为官方推荐的SMTP服务器
Outlook/Office 365官方推荐使用smtp.office365.com作为SMTP服务器,替换原Host:
$mail->Host = 'smtp.office365.com';
4. 使用应用密码(若开启MFA)
如果沙箱邮箱启用了多因素认证(MFA),直接使用原密码会失败,需在微软账户中创建应用密码,替换代码中的Password值。
5. 在Exchange管理中心启用SMTP AUTH
登录Exchange Admin Center,找到对应邮箱账户,进入“邮件流”>“邮箱功能”,确保“SMTP AUTH”已启用。
内容的提问来源于stack exchange,提问作者MalcolmInTheCenter
相关产品推荐
相关产品推荐

