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

ASP.NET Core 2.1无UI后端Gmail SMTP OAuth2.0邮件发送实现指导

ASP.NET Core 2.1 纯后端实现Gmail SMTP OAuth2.0邮件发送

一、谷歌云平台前置配置

  • 登录谷歌云控制台,创建新项目后搜索并启用Gmail API
  • 创建服务账号,生成JSON格式的密钥文件,下载后放到后端项目可访问目录
  • 若使用谷歌工作区(原G Suite)账号作为发件人,需为服务账号配置域范围授权:在工作区管理后台,将服务账号客户端ID与https://mail.google.com/权限绑定,并指定允许模拟的发件人邮箱

    注:普通个人Gmail账号无法使用域范围授权,需采用下文的桌面应用令牌替代方案

二、代码实现步骤

  1. 安装必要NuGet包
    控制台执行:

    Install-Package Google.Apis.Auth
    Install-Package Google.Apis.Gmail.v1
    
  2. 配置应用参数
    在appsettings.json中添加Gmail相关配置:

    "GmailSettings": {
      "ServiceAccountKeyPath": "keys/service-account.json",
      "FromEmail": "sender@your-domain.com",
      "SmtpHost": "smtp.gmail.com",
      "SmtpPort": 587
    }
    
  3. 编写邮件发送服务
    创建GmailOAuth2Sender类,封装令牌获取和邮件发送逻辑:

    using Google.Apis.Auth.OAuth2;
    using Microsoft.Extensions.Configuration;
    using System.Net;
    using System.Net.Mail;
    using System.Threading.Tasks;
    
    public class GmailOAuth2Sender
    {
        private readonly IConfiguration _configuration;
    
        public GmailOAuth2Sender(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    
        public async Task SendEmailAsync(string toEmail, string subject, string htmlBody)
        {
            // 加载服务账号凭证并模拟发件人
            var credential = GoogleCredential.FromFile(_configuration["GmailSettings:ServiceAccountKeyPath"])
                .CreateScoped(new[] { "https://mail.google.com/" })
                .CreateWithUser(_configuration["GmailSettings:FromEmail"]);
    
            // 获取OAuth2访问令牌
            var accessToken = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
    
            // 配置SMTP客户端
            using var smtpClient = new SmtpClient(_configuration["GmailSettings:SmtpHost"], int.Parse(_configuration["GmailSettings:SmtpPort"]))
            {
                EnableSsl = true,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(_configuration["GmailSettings:FromEmail"], accessToken, "Bearer")
            };
    
            // 构建邮件内容
            var mailMessage = new MailMessage
            {
                From = new MailAddress(_configuration["GmailSettings:FromEmail"]),
                Subject = subject,
                Body = htmlBody,
                IsBodyHtml = true
            };
            mailMessage.To.Add(toEmail);
    
            // 发送邮件
            await smtpClient.SendMailAsync(mailMessage);
        }
    }
    
  4. 注册服务依赖
    在Startup.cs的ConfigureServices方法中添加:

    services.AddScoped<GmailOAuth2Sender>();
    

三、个人Gmail账号替代方案

如果是普通个人Gmail账号,无法使用域范围授权,可采用桌面应用OAuth流:

  1. 在谷歌云控制台创建桌面应用类型的客户端ID和密钥
  2. 手动触发授权流程获取refresh_token(可通过谷歌OAuth2 playground完成,需勾选https://mail.google.com/权限)
  3. 后端通过refresh_token定期获取access_token,示例代码:
    using System.Net.Http;
    using System.Net.Http.Json;
    using System.Threading.Tasks;
    
    public class GmailPersonalSender
    {
        private readonly IConfiguration _config;
        private readonly HttpClient _httpClient;
    
        public GmailPersonalSender(IConfiguration config, HttpClient httpClient)
        {
            _config = config;
            _httpClient = httpClient;
        }
    
        private async Task<string> GetAccessTokenAsync()
        {
            var tokenRequest = new
            {
                client_id = _config["GmailPersonal:ClientId"],
                client_secret = _config["GmailPersonal:ClientSecret"],
                refresh_token = _config["GmailPersonal:RefreshToken"],
                grant_type = "refresh_token",
                scope = "https://mail.google.com/"
            };
    
            var response = await _httpClient.PostAsJsonAsync("https://oauth2.googleapis.com/token", tokenRequest);
            response.EnsureSuccessStatusCode();
    
            var tokenData = await response.Content.ReadFromJsonAsync<TokenResponse>();
            return tokenData.AccessToken;
        }
    
        // SendEmailAsync方法逻辑同前文,替换获取token的部分即可
    }
    
    public class TokenResponse
    {
        public string AccessToken { get; set; }
        public int ExpiresIn { get; set; }
    }
    

关键注意事项

  • 令牌有效期为1小时,建议添加缓存逻辑避免重复请求谷歌令牌服务
  • 确保发件人邮箱已启用Gmail API访问权限
  • 服务账号密钥文件需妥善保管,避免泄露

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:20:18