C# .Net中MailKit调用smtp.Connect连接Office365 SMTP抛出异常求助
MailKit 连接 Office365 SMTP 超时解决方案
问题根因&修复步骤
- 删掉重复的
Connect调用:现有代码中在try块内连续调用了两次smtp.Connect,第一次连接建立后重复发起连接请求会触发Office365 SMTP服务端的临时限流规则,直接导致第二次连接超时。 - 显式指定TLS模式:不要使用
SecureSocketOptions.Auto自动协商,Office365的587端口要求使用STARTTLS模式,修改为SecureSocketOptions.StartTls即可避免协商失败导致的超时。 - 禁用默认代理继承:MailKit默认会继承.NET运行时的全局代理配置,若环境配置的代理规则未放行MailKit的请求,就算telnet测试正常也会出现连接超时,可手动指定不使用代理:
smtp.ProxyClient = null; - 强制启用TLS 1.2:Office365要求所有连接最低使用TLS 1.2版本,若运行时默认禁用了高版本TLS,需在程序初始化阶段添加配置:
System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12;
修正后可运行代码
public void ConnectSmtpServer() { using MailKit.Net.Smtp; string _SmtpServer = "smtp.office365.com"; int _portNumber = 587; Console.WriteLine("Welcome!"); // 全局配置TLS版本,也可以放在程序启动入口处 System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12; using (SmtpClient smtp = new SmtpClient()) { try { smtp.Timeout = 30 * 1000; // 禁用代理继承 smtp.ProxyClient = null; // 显式指定STARTTLS模式,仅调用一次Connect smtp.Connect(_SmtpServer, _portNumber, SecureSocketOptions.StartTls); Console.WriteLine("Test smtp connection using MailKit.Net !"); Console.WriteLine(); // 后续认证、发信逻辑可在此处添加 // smtp.Authenticate(yourEmail, yourAppPassword); // 用完断开连接 smtp.Disconnect(true); } catch (Exception ex) { Console.WriteLine($"连接失败:{ex.Message}"); } } }
额外注意事项
- Office365现在默认禁用账号的SMTP基础认证,你需要在Microsoft 365 admin中心为对应账号开启SMTP AUTH权限,开启了多因素认证的账号必须使用应用密码完成认证。
- 若以上步骤都操作后仍超时,可临时把超时时间调整为60秒再测试,部分网络环境下TLS握手耗时较长会超出30秒阈值。
内容的提问来源于stack exchange,提问作者Pradeep Bansal
相关产品推荐
相关产品推荐

