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

C#使用SmtpClient发Gmail遇认证问题,求替代实现方案

解决Gmail SMTP认证失败(5.7.0 Authentication Required)的替代方案

谷歌在2022年5月30日停止支持仅通过用户名+密码登录的第三方SMTP应用,这直接导致你原有的SmtpClient代码触发认证错误。以下是几种可行的替代方案:

方案1:使用应用专用密码(需开启两步验证)

  • 前提:你的Gmail账户已开启两步验证(2FA)
  • 操作流程:
    1. 登录谷歌账户的「安全」设置页
    2. 找到「应用专用密码」选项,生成一个用于邮件发送的专用密码
    3. 将原代码中的password参数替换为这个专用密码,其余代码无需修改

方案2:使用Google Workspace SMTP(企业/教育账户)

如果你的账户属于Google Workspace(原G Suite),可通过管理员配置允许SMTP登录:

  1. 登录Google Workspace管理控制台,进入「应用」>「Gmail」>「高级设置」
  2. 启用「SMTP中继服务」,配置允许的发件人IP或验证规则
  3. 原代码保持不变,使用Workspace账户的用户名和密码即可(需确保账户未被限制SMTP访问权限)

方案3:使用Gmail API发送邮件(谷歌官方推荐)

这是最安全且长期支持的方案,适合需要持续维护的应用:

实现步骤:

  1. 在Google Cloud控制台创建项目,启用Gmail API
  2. 创建OAuth 2.0客户端ID,下载客户端密钥文件(JSON格式)
  3. 安装Google.Apis.Gmail.v1 NuGet包,实现发送逻辑

示例代码:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using System.IO;
using System.Net.Mail;
using System.Threading.Tasks;

public static async Task SendEmailWithGmailApi(string fromAddress, string clientSecretFilePath)
{
    UserCredential credential;
    using (var stream = new FileStream(clientSecretFilePath, FileMode.Open, FileAccess.Read))
    {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            new[] { GmailService.Scope.GmailSend },
            "user",
            System.Threading.CancellationToken.None);
    }

    var gmailService = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "你的应用名称"
    });

    var mailMessage = new MailMessage(fromAddress, GetToAddress(), "邮件主题", "邮件内容");
    using (var memoryStream = new MemoryStream())
    {
        mailMessage.Save(memoryStream);
        var gmailApiMessage = new Message
        {
            Raw = Convert.ToBase64String(memoryStream.ToArray())
        };
        await gmailService.Users.Messages.Send(gmailApiMessage, "me").ExecuteAsync();
    }
}

方案对比:

  • 应用专用密码:改动最小,快速生效,但必须开启两步验证
  • Google Workspace SMTP:适合企业场景,代码无需大改
  • Gmail API:安全合规,谷歌长期支持,但需要处理OAuth授权流程,实现稍复杂

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 18:15:38