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

使用Nodemailer与Gmail发信时遇unauthorized_client错误求助

问题分析

你遇到的unauthorized_client错误主要由三个核心原因导致:

  1. 代码中包含无效的Gmail API授权Scope,且OAuth2配置存在字段错误
  2. Google Workspace账号未完成服务账号的域范围委派配置
  3. 普通个人Gmail账号误用了仅适用于Workspace的服务账号方案

修复指导

一、修正代码中的错误

1. 清理无效Scope

移除Scopes数组中的无效项"https://gmail.googleapis.com",保留必要的权限范围:

scopes: [
  "https://mail.google.com/",
  "https://www.googleapis.com/auth/gmail.send",
],

2. 修正OAuth2配置

修复accessToken字段的错误赋值,同时确保服务账号正确模拟目标发信邮箱:

// 初始化服务账号认证(替换为你的密钥文件路径)
const auth = new GoogleAuth({
  scopes: [
    "https://mail.google.com/",
    "https://www.googleapis.com/auth/gmail.send",
  ],
  keyFile: "./path/to/your-service-account-key.json",
});
const client = await auth.getClient();

// 服务账号必须模拟目标发信邮箱(仅Workspace账号支持)
await client.requestAccessToken({
  subject: "mygmailid@gmail.com"
});

// 修正Nodemailer配置
const transporter = createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  priority: "high",
  auth: {
    type: "OAuth2",
    user: "mygmailid@gmail.com",
    serviceClient: client.client_id,
    privateKey: client.private_key.replace(/\\n/g, "\n"), // 修正私钥换行符格式
    accessToken: client.credentials.access_token,
    expires: client.credentials.expiry_date,
  },
  transactionLog: true,
});

二、Workspace账号专属配置

如果使用Google Workspace(原G Suite)账号,需完成域范围委派:

  1. 登录Google Cloud控制台,找到你的服务账号,点击「编辑」,勾选「启用G Suite域范围委派」
  2. 登录Workspace管理员控制台,进入「安全」→「API控制」→「域范围委派」:
    • 添加服务账号的Client ID
    • 授权Scope:https://mail.google.com/ 或 https://www.googleapis.com/auth/gmail.send
    • 保存配置

三、普通个人Gmail账号替代方案

普通个人Gmail账号不支持服务账号委派,需改用OAuth2授权码流程:

  1. 在Google Cloud控制台创建「OAuth 2.0客户端ID」(选择「桌面应用」类型)
  2. 通过Google OAuth Playground或代码获取refresh_token
  3. 修改Nodemailer的auth配置:
auth: {
  type: "OAuth2",
  user: "mygmailid@gmail.com",
  clientId: "YOUR_OAUTH_CLIENT_ID",
  clientSecret: "YOUR_OAUTH_CLIENT_SECRET",
  refreshToken: "YOUR_REFRESH_TOKEN",
}

四、验证前置条件

  • 确认Google Cloud项目已启用Gmail API
  • 服务账号密钥文件路径正确、未损坏
  • 发信邮箱未开启「不太安全的应用访问」(OAuth2流程无需开启)

内容的提问来源于stack exchange,提问作者Muhammad Hassaan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:55:06