使用SmtpClient发送邮箱验证码遇Connection reset by peer报错求解决
无法通过SMTP发送邮箱验证码:Connection reset by peer错误解决
我尝试通过SMTP发送邮箱验证码,但功能无法正常运行,以下是我的C#实现代码:
public static void SendVerificationEmail(string email, string code) { var fromAddress = new MailAddress("my_email_example@gmail.com", "ExampleApp"); var toAddress = new MailAddress(email); const string fromPassword = "my-email-password"; const string subject = "Email Verification"; string body = $"Your verification code is {code}"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); } }
调用该方法时抛出以下错误:
System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer
请问该如何解决这个问题?
解决方法
1. 配置Gmail应用专用密码
Gmail默认禁止低安全应用直接使用原密码登录,需按以下步骤操作:
- 开启Google账号的两步验证
- 在Google账号的「安全」设置中生成应用专用密码,替换代码中的
my-email-password
2. 修正SMTP客户端配置顺序
确保UseDefaultCredentials先设为false,再赋值Credentials,顺序错误会导致验证失效:
var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, // 先设置这一项 Credentials = new NetworkCredential(fromAddress.Address, "应用专用密码") };
3. 排查网络限制
- 部分公司/校园网络会拦截587、465端口,切换到个人热点或家庭网络测试
- 临时关闭本地防火墙、杀毒软件,确认是否是它们阻止了SMTP连接
4. 替换为MailKit库(推荐)
.NET官方的SmtpClient已被标记为过时,推荐使用更稳定的第三方库MailKit:
- 安装NuGet包:
Install-Package MailKit - 替换实现代码:
using MailKit.Net.Smtp; using MimeKit; public static void SendVerificationEmail(string email, string code) { var message = new MimeMessage(); message.From.Add(new MailboxAddress("ExampleApp", "my_email_example@gmail.com")); message.To.Add(new MailboxAddress("", email)); message.Subject = "Email Verification"; message.Body = new TextPart("plain") { Text = $"Your verification code is {code}" }; using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587, true); client.Authenticate("my_email_example@gmail.com", "应用专用密码"); client.Send(message); client.Disconnect(true); } }
5. 检查Google账号安全状态
登录Google账号,查看是否有异常登录拦截记录,按照页面提示解除安全限制
内容的提问来源于stack exchange,提问作者İrem Kürkeçi
相关产品推荐
相关产品推荐

