.NET应用通过SmtpClient发送邮件时出现Service not available错误求助
解决.NET中SmtpClient发送Gmail邮件时的"Service not available"错误
核心问题与修复方案
1. Gmail已停用"低安全性应用"权限
Gmail在2022年起已彻底停止支持"低安全性应用"访问,即便你在账户设置中开启该选项也无法生效。需改用应用专用密码:
- 确保Google账户已开启两步验证
- 进入Google账户「安全」设置,找到「应用专用密码」选项
- 创建一个用于邮件发送的专用密码,替换代码中的普通账户密码
2. 替换过时的SmtpClient为MailKit
System.Net.Mail.SmtpClient已被标记为过时,第三方库MailKit对现代SMTP协议支持更完善,能有效避免连接问题。
安装MailKit
Install-Package MailKit
重构后的邮件发送代码
using MailKit.Net.Smtp; using MimeKit; public class EmailService { private readonly IConfiguration _configuration; private readonly ILogger<EmailService> _logger; public EmailService(IConfiguration configuration, ILogger<EmailService> logger) { _configuration = configuration; _logger = logger; } public async Task<EmailResponse> SendEmailAsync(EmailRequest emailRequest) { var config = _configuration.GetSection("EmailConfig").Get<EmailConfig>(); if (config == null) { _logger.LogError("无可用邮件配置"); throw new ArgumentNullException(nameof(config), "无可用邮件配置"); } var message = new MimeMessage(); message.From.Add(new MailboxAddress(emailRequest.SenderName, emailRequest.Sender)); foreach (var recipient in emailRequest.Receipient) { message.To.Add(new MailboxAddress("", recipient)); } message.Subject = emailRequest.Subject; message.Body = new TextPart("plain") { Text = emailRequest.Body }; using (var client = new SmtpClient()) { try { await client.ConnectAsync("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.StartTls); await client.AuthenticateAsync(config.Username, config.AppPassword); await client.SendAsync(message); await client.DisconnectAsync(true); _logger.LogInformation("邮件发送成功"); return new EmailResponse { Status = "successful", Message = "邮件发送成功" }; } catch (SmtpException smtpEx) { _logger.LogError(smtpEx, "SMTP错误:邮件发送失败"); return new EmailResponse { Status = "failed", Message = smtpEx.Message }; } catch (Exception ex) { _logger.LogError(ex, "未知错误:邮件发送失败"); return new EmailResponse { Status = "failed", Message = ex.Message }; } } } }
3. 排查网络层面限制
- 检查本地/服务器防火墙是否封禁了587端口
- 测试能否通过telnet连接
smtp.gmail.com 587,确认网络连通性 - 云服务器用户需检查安全组规则,允许出站SMTP流量(587端口)
4. 可选:使用OAuth2验证(更高安全级别)
若需更安全的验证方式,可通过Google Cloud控制台创建OAuth2凭据,结合MailKit实现OAuth2登录流程,避免使用明文密码。
内容的提问来源于stack exchange,提问作者tea-code lab
相关产品推荐
相关产品推荐

