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

如何在C#中自动下载Google Cloud的Gmail Credentials.json文件

实现无交互自动获取Gmail凭据并发送邮件的C#方案

核心思路

要替代手动创建credentials.json的操作并实现无交互运行,不能依赖需要浏览器授权的GoogleWebAuthorizationBroker,需根据账号类型选择两种方案:个人Gmail账号用OAuth2离线模式(预获取一次刷新令牌),Google Workspace账号用服务账号域授权(完全无交互)。


方案一:OAuth2离线模式(个人Gmail账号)

先手动执行一次授权流程获取刷新令牌,后续即可无交互自动刷新凭据。

完整代码

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.Threading;

class GmailSender
{
    // 替换为你的Google Cloud客户端信息和预获取的刷新令牌
    private const string ClientId = "YOUR_CLIENT_ID";
    private const string ClientSecret = "YOUR_CLIENT_SECRET";
    private const string RefreshToken = "YOUR_REFRESH_TOKEN";
    private static readonly string[] Scopes = { GmailService.Scope.GmailSend };

    // 无交互发送邮件
    public static void SendEmail()
    {
        // 构建自动刷新的凭据
        var credential = new UserCredential(new GoogleAuthorizationCodeFlow(
            new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = ClientId,
                    ClientSecret = ClientSecret
                },
                Scopes = Scopes
            }), "user", new TokenResponse { RefreshToken = RefreshToken });

        // 初始化Gmail服务
        var service = new GmailService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = "自定义邮件应用名称"
        });

        // 构建邮件内容并编码
        var message = new Message();
        message.Raw = Base64UrlEncode($"From: 你的邮箱地址\r\nTo: 收件人邮箱地址\r\nSubject: 测试邮件\r\n\r\n这是无交互发送的测试邮件");

        // 发送邮件
        service.Users.Messages.Send(message, "me").Execute();
    }

    // 仅首次运行:获取并保存刷新令牌
    public static void GetRefreshToken()
    {
        var credentialParameters = new ClientSecrets
        {
            ClientId = ClientId,
            ClientSecret = ClientSecret
        };

        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            credentialParameters,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore("Gmail.Auth.Store")).Result;

        // 控制台输出刷新令牌,复制保存后即可注释此方法
        System.Console.WriteLine("Refresh Token: " + credential.Token.RefreshToken);
    }

    // 邮件内容Base64Url编码工具
    private static string Base64UrlEncode(string input)
    {
        var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
        return System.Convert.ToBase64String(inputBytes)
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");
    }
}

使用说明

  1. 首次运行时调用GetRefreshToken(),会弹出浏览器授权,完成后控制台输出刷新令牌,将其填入代码对应位置
  2. 后续直接调用SendEmail()即可无交互发送邮件,无需手动创建credentials.json

方案二:服务账号授权(Google Workspace账号)

适用于企业G Suite账号,可实现完全无交互,无需手动获取令牌。

完整代码

using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using System.IO;

class GmailServiceAccountSender
{
    private const string ServiceAccountKeyPath = "path_to_service_account_key.json"; // 替换为服务账号密钥文件路径
    private const string UserToImpersonate = "你的Workspace邮箱地址";
    private static readonly string[] Scopes = { GmailService.Scope.GmailSend };

    public static void SendEmail()
    {
        // 加载服务账号密钥并模拟指定用户
        var credential = GoogleCredential.FromFile(ServiceAccountKeyPath)
            .CreateScoped(Scopes)
            .CreateWithUser(UserToImpersonate);

        // 初始化Gmail服务
        var service = new GmailService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = "自定义邮件应用名称"
        });

        // 构建并发送邮件
        var message = new Message();
        message.Raw = Base64UrlEncode($"From: {UserToImpersonate}\r\nTo: 收件人邮箱地址\r\nSubject: 服务账号测试邮件\r\n\r\n这是无交互发送的邮件");

        service.Users.Messages.Send(message, "me").Execute();
    }

    private static string Base64UrlEncode(string input)
    {
        var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
        return System.Convert.ToBase64String(inputBytes)
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");
    }
}

使用说明

  1. 在Google Cloud控制台创建服务账号并下载JSON格式的密钥文件
  2. 在Google Workspace admin控制台给服务账号开启域范围委派,并授权Gmail发送权限
  3. 将密钥文件路径填入代码,直接调用SendEmail()即可无交互运行

注意事项

  • 需提前在Google Cloud控制台启用Gmail API
  • 个人账号的刷新令牌长期有效,除非用户主动撤销授权
  • 服务账号仅支持Google Workspace账号,个人Gmail账号无法使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:40:30