PowerShell脚本用Office365 SMTP发邮件遇连接及认证错误求助
Office 365 SMTP发送邮件认证失败问题解决建议
一、账号与认证核心排查
- 若账号启用了多因素认证(MFA),禁止直接使用用户登录密码,必须使用该账号的应用密码(登录微软账号管理后台,在“安全”选项中生成)。
- 检查租户级SMTP基本认证开关:即使单个用户
SmtpClientAuthenticationDisabled设为False,租户层面禁用仍会导致失败。执行以下命令确认并修改:# 查看租户SMTP认证状态 Get-TransportConfig | Select-Object SmtpClientAuthenticationDisabled # 若返回True,执行下面命令开启 Set-TransportConfig -SmtpClientAuthenticationDisabled $False
二、修正SMTP客户端配置
确保PowerShell中SmtpClient配置完全符合Office 365规范:
- 固定SMTP服务器为
smtp.office365.com,端口587 - 必须启用
EnableSsl=$true,部分环境需显式触发STARTTLS - 凭证需正确传递,示例代码片段:
$smtpServer = "smtp.office365.com" $smtpPort = 587 $smtpUsername = "your-account@domain.com" # MFA账号填应用密码,非MFA填用户密码 $smtpPassword = ConvertTo-SecureString "your-credential" -AsPlainText -Force $smtpCreds = New-Object System.Management.Automation.PSCredential ($smtpUsername, $smtpPassword) $smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer, $smtpPort) $smtpClient.EnableSsl = $true $smtpClient.Credentials = $smtpCreds
三、额外排查项
- 网络连通性测试:执行
Test-NetConnection smtp.office365.com -Port 587,确认机器能正常访问该端口,无防火墙/代理拦截。 - 发件人一致性:发件人邮箱必须与认证账号完全匹配,不能使用别名或其他邮箱。
- 账号权限检查:确认账号未被限制发送邮件,执行命令查看状态:
Get-Mailbox -Identity "your-account@domain.com" | Select-Object RecipientTypeDetails, SendAsPermissions
内容的提问来源于stack exchange,提问作者John John
相关产品推荐
相关产品推荐

