使用 nodejs 中的服务帐户域范围委派通过 Google Apps Gmail 发送邮件 [英] Send mail via Google Apps Gmail using service account domain wide delegation in nodejs

查看:34
本文介绍了使用 nodejs 中的服务帐户域范围委派通过 Google Apps Gmail 发送邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been reading tutorials and seeing examples for 2 days already, with no success. I want to send an email using Google Apps Gmail account in NodeJS environment, however, i get 400 response from Google API:

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

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

Here's what I've done so far:

  1. 在 Google Cloud Platform 中创建了一个项目
  2. 创建了一个服务帐号
  3. 为服务帐户启用Domain Wide委派
  4. JSON 格式下载服务帐号的密钥
  5. API Manager > Credentials 我已经创建了 OAuth 2.0 客户端 ID
  6. 为项目启用 Gmail API
  1. Created a project in Google Cloud Platform
  2. Created a service account
  3. Enabled Domain Wide Delegation for the service account
  4. Downloaded the key for the service account in JSON format
  5. API Manager > Credentials i have created OAuth 2.0 client ID
  6. Enabled Gmail API for the project

在 Google Apps 管理控制台中:

In Google Apps Admin console:

  1. Security > Advanced Settings > Manage API client access 我已经添加了步骤 Client IDcode>4 以上
  2. 我已为 Client ID
  3. 添加了所有可能的范围
  1. In Security > Advanced Settings > Manage API client access i have added the Client ID from step 4 above
  2. I have added all possible scopes for the Client ID

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

Here's the code that tries to send an email:

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 消息,并且请求使用正确初始化的令牌发送:

I can see the Google auth success message and the request is sent with properly initialized 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); 我没有提到要模拟的帐户.

So I was half-step close to the solution, the problem was that while creating const jwtClient = new google.auth.JWT(googleKey.client_email, null, googleKey.private_key, ['https://www.googleapis.com/auth/gmail.send'], null); i did not mention the account to be impersonated.

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

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

To summarize, the correct steps are:

  1. 在 Google Cloud Platform 中创建了一个项目
  2. 创建了一个服务帐号
  3. 为服务帐户启用Domain Wide委派
  4. 以 JSON 格式下载服务帐号的密钥
  5. API Manager > Credentials 我已经创建了 OAuth 2.0 客户端 ID
  6. 为项目启用 Gmail API
  1. Created a project in Google Cloud Platform
  2. Created a service account
  3. Enabled Domain Wide Delegation for the service account
  4. Downloaded the key for the service account in JSON format
  5. API Manager > Credentials i have created OAuth 2.0 Client ID
  6. Enabled Gmail API for the project

在 Google Apps 管理控制台中:

In Google Apps Admin console:

  1. Security > Advanced Settings > Manage API client access 我从第 4 步添加了 Client ID以上
  2. 我已为 Client ID
  3. 添加了所有可能的范围
  1. In Security > Advanced Settings > Manage API client access i have added the Client ID from step 4 above
  2. I have added all possible scopes for the 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);
     }
 });

希望对其他人有所帮助

这篇关于使用 nodejs 中的服务帐户域范围委派通过 Google Apps Gmail 发送邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆