You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Windows应用发送邮件出现SMTP认证错误,如何解决?

问题描述

开发Windows应用时,点击“忘记密码”提交邮箱后,触发SMTP认证错误,错误信息:

SmtpException has occured: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.

使用的代码如下:

try
{
    Cursor = Cursors.WaitCursor;

    MailAddress from = new MailAddress("bgatt64@gmail.com", "Bob Gatto");
    MailAddress to = new MailAddress("bgatto64@yahoo.com", "Bob Gatto");

    MailMessage eMsg = new MailMessage(from, to);
    eMsg.Subject = "Your Password Renewal Request";
    eMsg.IsBodyHtml = true;
    eMsg.Body = "This is the body.";

    SmtpClient eClient = new SmtpClient("smtp.gmail.com", 587);
    eClient.EnableSsl = true;
    eClient.UseDefaultCredentials = true;

    // The following email and password used is that of my own gmail email
    // that I use for my own personal email.

    eClient.Credentials = new System.Net.NetworkCredential("<MyOwnEmail@gmail.com>", "<MyPassword>");
    eClient.Send(eMsg);
}
catch (SmtpException ex)
{
    throw new ApplicationException("SmtpException has occurred: " + ex.Message);
}
catch (Exception ex)
{
    throw ex;
}
解决步骤
  • 修正Credentials赋值顺序:代码里先设UseDefaultCredentials = true再赋值自定义认证信息,会导致自定义Credentials被覆盖。必须先把UseDefaultCredentials设为false,再设置认证信息:

    eClient.UseDefaultCredentials = false;
    eClient.Credentials = new System.Net.NetworkCredential("<你的Gmail邮箱>", "<你的应用专用密码>");
    
  • 启用Gmail应用专用密码:

    1. 登录你的Gmail账号,开启两步验证(这是生成应用专用密码的前提)。
    2. 进入Google账号安全设置,找到“应用专用密码”选项,生成一个仅用于该Windows应用的密码。
    3. 代码中用这个应用专用密码替换普通Gmail登录密码——现在普通密码无法直接用于SMTP认证。
  • 统一发件人与认证账号:确保from地址和你用于认证的Gmail邮箱完全一致,Gmail SMTP要求发件人必须和认证账号匹配。

  • 保留正确的SMTP配置:当前代码里smtp.gmail.com端口587、EnableSsl = true的设置是正确的,无需修改。

内容的提问来源于stack exchange,提问作者user19866451

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:01:41