node.js - 使用 nodejs 中的服务帐户域范围委托(delegate)通过 Google Apps Gmail 发送邮件

标签 node.js gmail google-apps jwt service-accounts

我已经阅读教程和查看示例 2 天了,但没有成功。 我想在 NodeJS 环境中使用 Google Apps Gmail 帐户发送电子邮件,但是,我得到 400来自 Google API 的响应:

{[Error: Bad Request]
code: 400,
errors:
  [{ 
    domain: 'global',
    reason: 'failedPrecondition',
    message: 'Bad Request'
  }]
}

这是我到目前为止所做的:

  1. 在 Google Cloud Platform 中创建了一个项目
  2. 创建服务帐号
  3. 已启用 Domain Wide Delegation对于服务帐户
  4. JSON 中下载了服务帐户的 key 格式
  5. API Manager > Credentials我创造了OAuth 2.0 client ID
  6. 为项目启用 Gmail API

在 Google Apps 管理控制台中:

  1. Security > Advanced Settings > Manage API client access我添加了 Client ID从步骤 4以上
  2. 我已经为 Client ID 添加了所有可能的范围

这是尝试发送电子邮件的代码:

const google = require('googleapis');
const googleKey = require('./google-services.json');
const jwtClient = new google.auth.JWT(googleKey.client_email, null, googleKey.private_key, ['https://www.googleapis.com/auth/gmail.send'], null);

jwtClient.authorize((err, tokens) => {
  if (err) {
    console.err(err);
    return;
  }
  console.log('Google auth success')
  var gmail = google.gmail({version: 'v1', auth: jwtClient})
  var raw = <build base64 string according to RFC 2822 specification>

  var sendMessage = gmail.users.messages.send({
    auth: jwtClient,
    userId: 'user@domain.com',
    message: {
      raw: raw
    }
  }, (err, res) => {
    if (err) {
      console.error(err);
    } else {
      console.log(res);
    }
});

我可以看到 Google auth success消息并使用正确初始化的 token 发送请求:

headers:
{ Authorization: 'Bearer ya29.CjLjAtVjGNJ8fcBnMSS8AEXAvIm4TbyNTc6g_S99HTxRVmzKpWrAv9ioTI4BsLKXW7uojQ',
 'User-Agent': 'google-api-nodejs-client/0.9.8',
 host: 'www.googleapis.com',
 accept: 'application/json',
 'content-type': 'application/json',
 'content-length': 2 }

但是,响应仍然是 400

最佳答案

所以我接近解决方案了半步,问题是在创建 const jwtClient = new google.auth.JWT(googleKey.client_email, null, googleKey.private_key, ['https://www .googleapis.com/auth/gmail.send'], null); 我没有提到要模拟的帐户。

正确的初始化应该是: const jwtClient = new google.auth.JWT(googleKey.client_email, null, googleKey.private_key, ['https://www.googleapis.com/auth/gmail.send'], 'user@domain.com' );

总而言之,正确的步骤是:

  1. 在 Google Cloud Platform 中创建了一个项目
  2. 创建服务帐号
  3. 为服务帐户启用域范围委派
  4. 以 JSON 格式下载服务帐户的 key
  5. API Manager > Credentials 我已经创建了 OAuth 2.0 Client ID
  6. 为项目启用 Gmail API

在 Google Apps 管理控制台中:

  1. Security > Advanced Settings > Manage API client access 我添加了第 4 步中的 Client ID以上
  2. 我已经为 Client ID 添加了所有可能的范围

这是发送邮件的代码:

const google = require('googleapis');
const googleKey = require('./google-services.json');
const jwtClient = new google.auth.JWT(googleKey.client_email, null, googleKey.private_key, ['https://www.googleapis.com/auth/gmail.send'], '<user to impersonate>');

jwtClient.authorize((err, tokens) => {
  if (err) {
    console.err(err);
    return;
  }
  console.log('Google auth success')
  var gmail = google.gmail({version: 'v1'})
  var raw = <build base64 string according to RFC 2822 specification>

  var sendMessage = gmail.users.messages.send({
    auth: jwtClient,
    userId: '<user to impersonate>',
    resource: {
      raw: raw
    }
  }, (err, res) => {
     if (err) {
       console.error(err);
     } else {
       console.log(res);
     }
 });

希望对其他人有帮助

关于node.js - 使用 nodejs 中的服务帐户域范围委托(delegate)通过 Google Apps Gmail 发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37243862/

相关文章:

css - 编码 HTML 电子邮件 - 添加图像轮廓/边框 - gmail 和 Outlook

Gmail - 有什么方法可以让我们知道我们收到的电子邮件是否被退回?

openid - 如何将 Google 联合登录限制到特定的 Apps 域?

email - 什么电子邮件服务器或在线电子邮件服务允许为收件箱创建无限的电子邮件别名(通过 API)

java - Gmail API 获取邮件 'cannot resolve method execute()'

javascript - NPM/错误 : EACCES: permission denied, 扫描目录

java - redis 集合成员更新的高效方式

javascript - express.index 发送 json 对象时出现问题

windows - 在 Windows 上从 Eclipse 复制粘贴到 Gmail 时保留文本颜色?

node.js - 出现此错误 "UNMET PEER DEPENDENCY grunt@1.0.1"