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

C#通过SMTP发送Gmail邮件遇认证失败,求当前可行解决方案

在C#中发送Gmail邮件的当前解决方案

你的代码抛出SmtpException是因为Google已移除低安全性应用访问选项,且App Password的使用有特定前提,以下是两种可行方案:

方案一:使用App Password(仅个人账号,需开启两步验证)

  • 前提:你的Google账号必须开启两步验证(2FA),且为个人账号(Google Workspace账号需管理员后台授权)
  • 操作步骤:
    1. 登录Google账号安全设置,找到「应用密码」入口(未开启2FA则不会显示该选项)
    2. 创建应用密码:选择「邮件」应用,设备类型选「其他」,生成16位无空格密码
    3. 将原代码中NetworkCredential的Password替换为这个生成的应用密码,其余代码无需修改

方案二:使用OAuth2.0认证(推荐,支持所有账号类型)

由于.NET中的SmtpClient已被标记为过时,推荐使用MailKit库实现OAuth2.0认证,这也是Google官方推荐的安全方式:

步骤1:安装依赖包

通过NuGet安装以下包:

Install-Package MailKit
Install-Package MimeKit
Install-Package Google.Apis.Gmail.v1
Install-Package Google.Apis.Auth

步骤2:获取OAuth2.0凭据

  1. 登录Google Cloud Console,创建新项目
  2. 搜索并启用「Gmail API」
  3. 创建「OAuth客户端ID」,应用类型选择「桌面应用」
  4. 下载凭据JSON文件,重命名为credentials.json并放在项目根目录

步骤3:编写发送代码

using System;
using System.IO;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;

class Program
{
    static readonly string[] Scopes = { "https://mail.google.com/" };
    static readonly string AppName = "Gmail邮件发送工具";

    static async Task Main(string[] args)
    {
        Console.WriteLine("Start......*******");

        // 加载OAuth2凭据
        UserCredential credential;
        using var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read);
        var credPath = "token.json";
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            System.Threading.CancellationToken.None,
            new FileDataStore(credPath, true)).Result;

        // 构建邮件内容
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("发送者", "myGmail@gmail.com"));
        message.To.Add(new MailboxAddress("接收者", "hisGmail@gmail.com"));
        message.Subject = "Subject test";
        message.Body = new TextPart("plain") { Text = "Body test" };

        // 发送邮件
        using var client = new SmtpClient();
        await client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
        await client.AuthenticateAsync(new SaslMechanismOAuth2("myGmail@gmail.com", credential.Token.AccessToken));
        await client.SendAsync(message);
        await client.DisconnectAsync(true);

        Console.WriteLine("END*****");
    }
}

说明

  • 首次运行时会自动打开浏览器引导完成账号授权,授权成功后生成token.json文件,后续运行无需重复授权
  • OAuth2.0方式无需暴露账号密码,安全性更高,适配所有Google账号类型(包括Google Workspace)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:32:14