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

如何仅用服务账号凭据在ASP.NET Core控制台应用通过Gmail API发邮件?

实现方案

完全可以实现需求,有对应的官方及第三方NuGet包可直接使用,具体如下:

所需NuGet包

  • 谷歌官方Gmail API客户端包:Google.Apis.Gmail.v1,直接对接Gmail官方接口
  • 谷歌官方身份验证包:Google.Apis.Auth,用于服务账号凭据的授权验证,不需要走普通用户OAuth弹窗交互流程
  • (可选)邮件构造工具包:MimeKit,简化标准邮件内容的生成,避免手动处理邮件格式、编码的问题

前置配置要求

使用服务账号跨账号发邮件,需要先完成Google Workspace后台配置,否则会触发权限报错:

  • 给服务账号开启全域委托权限
  • 为服务账号分配https://www.googleapis.com/auth/gmail.send的API权限范围
  • 仅支持Google Workspace下的账号模拟发送,个人版Gmail账号无法使用该方案

核心实现逻辑

  1. 读取服务账号JSON凭据文件,创建授权凭证,指定要模拟的发件人邮箱地址:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Services;
using MimeKit;

// 加载服务账号凭据
var credential = GoogleCredential.FromFile("服务账号凭据文件路径.json")
    .CreateScoped(GmailService.Scope.GmailSend)
    .CreateWithUser("要模拟的发件人邮箱@yourdomain.com");
  1. 初始化Gmail服务客户端:
var gmailService = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "你的应用名称"
});
  1. 构造邮件并发送:
// 用MimeKit构造邮件
var message = new MimeMessage();
message.From.Add(new MailboxAddress("发件人名称", "要模拟的发件人邮箱@yourdomain.com"));
message.To.Add(new MailboxAddress("收件人名称", "收件人邮箱@domain.com"));
message.Subject = "邮件主题";
message.Body = new TextPart("plain") { Text = "邮件正文内容" };

// 转成Gmail API要求的Base64Url格式
using var stream = new MemoryStream();
message.WriteTo(stream);
var rawMessage = Convert.ToBase64String(stream.ToArray())
    .Replace('+', '-')
    .Replace('/', '_')
    .Replace("=", "");

// 调用发送接口
var gmailMessage = new Google.Apis.Gmail.v1.Data.Message { Raw = rawMessage };
gmailService.Users.Messages.Send(gmailMessage, "me").Execute();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:09:00