部署到服务器后无法通过SmtpClient发送邮件(Outlook SMTP认证失败)
问题
在Visual Studio的Release模式下启动项目时,我的SmtpClient可以正常发送邮件,但发布到亚马逊Ubuntu服务器后出现认证失败错误。更换其他SMTP服务商后可以正常发送,想了解Outlook SMTP无法工作的原因。
相关代码
using (MailMessage mail = new MailMessage()) using (SmtpClient smtpClient = new SmtpClient()) { smtpClient.Host = "smtp-mail.outlook.com"; smtpClient.Port = 587; smtpClient.Credentials = new NetworkCredential("mail", "password"); smtpClient.EnableSsl = true; mail.Body = $"Imie: {Name}, Mail: {Email}, Subcject: {Subject}, Comment: {Comment}"; mail.IsBodyHtml = false; mail.From = new MailAddress("mail", "Nowe zgłoszenie ze strony"); mail.To.Add("receiver"); mail.Subject = $"Nowe zgłoszenie ze strony"; smtpClient.Send(mail); }
服务器信息
- 操作系统:Ubuntu
- 托管平台:亚马逊
- 防火墙:无
报错信息
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HMKJSO3E4066", Request id "0HMKJSO3E4066:00000002": An unhandled exception was thrown by the application.
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 Client not authenticated to send mail. Error: 535 5.7.3 Authentication unsuccessful [BL1PR13CA0303.namprd13.prod.outlook.com]
原因分析
- 异地登录安全拦截:本地环境的IP是Outlook信任的常用地址,而亚马逊服务器的陌生IP触发了Outlook的安全机制,即使密码正确,也会被判定为可疑登录,拒绝认证。
- 两步验证与应用专用密码:如果你的Outlook账号开启了两步验证,直接使用账号密码做SMTP认证会失败。需要在微软账户后台生成应用专用密码替代普通密码。本地可能因为已通过设备信任验证,所以能正常发送,但服务器环境没有这个信任关系。
- TLS版本兼容性:旧版
SmtpClient默认TLS版本较低,Outlook SMTP服务器要求TLS 1.2及以上版本。服务器的.NET运行时可能未强制启用高版本TLS,导致安全握手失败,被服务器判定为未通过安全验证。 - 云IP发信限制:亚马逊云服务器的IP可能被Outlook纳入监控范围,这类IP常被用于批量发信,Outlook会限制其SMTP请求,即使凭据正确也会拒绝。
内容的提问来源于stack exchange,提问作者Software Architect
相关产品推荐
相关产品推荐

