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

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

问题描述

我一直在阅读教程和看过2天的例子,但没有成功。
我想在NodeJS环境中使用Google Apps Gmail帐户发送电子邮件,但是,我从Google API获得 400 响应:

  {[Error:Bad Request] 
code:400,
errors:
[{
domain:'全球',
原因:'failedPrecondition',
消息:'Bad Request'
}]
}

以下是我迄今为止所做的工作:


  1. 在Google Cloud中创建项目平台

  2. 为服务帐户创建服务帐户

  3. 启用域范围委派 li>
  4. JSON 格式下载服务帐户的密钥

  5. API经理> 凭证我已创建 OAuth 2.0客户端ID

  6. 为该项目启用了Gmail API

在Google Apps管理控制台中:


  1. 安全性> 高级S ettings > 管理API客户端访问我已经从步骤<$ c添加了客户端ID $ c> 4 以上

  2. 我为客户端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根据RFC 2822规范的字符串>

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

我可以看到 Google auth success 消息,并且请求以正确初始化的标记发送:

 头文件:
{授权:'承载者ya29.CjLjAtVjGNJ8fcBnMSS8AEXAvIm4TbyNTc6g_S99HTxRVmzKpWrAv9ioTI4BsLKXW7uojQ',
'User-Agent':'google-api-nodejs-客户机/ 0.9.8' ,
主机:'www.googleapis.com',
接受:'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');



<总之,正确的步骤是:
$ b


  1. 在Google Cloud Platform中创建项目

  2. 创建服务帐户
  3. 为服务帐户启用域范围委派
  4. 下载密钥为JSON格式的服务帐户

  5. API管理器> 凭证创建 OAuth 2.0客户端ID

  6. 为项目启用Gmail API

在Google Apps管理控制台中:


  1. 安全性> 高级设置> 管理API客户端访问我添加了客户端ID 从上面的步骤4开始

  2. 我添加了全部内容可能的作用域客户端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'],'<用户模仿>> ;');

jwtClient.authorize((err,tokens)=> {
if(err){
console.err(err);
return;
}
console.log('Google auth success')
var gmail = google.gmail({version:'v1'})
var raw =<根据RFC构建base64字符串2822规范>

var sendMessage = gmail.users.messages.send({
auth:jwtClient,
userId:'<要模仿的用户>',
资源:{
raw:raw
}
},(err,res)=> {
if(err){
console.error(err);
} else {
console.log(res);
}
});

希望对其他人有帮助


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. 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

In Google Apps Admin console:

  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);
    }
});

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 }

But still, the response is 400

解决方案

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.

The correct initialization should be: 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. 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

In Google Apps Admin console:

  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

This is the code that sends mails:

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);
     }
 });

Hope that would be helpful for others

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

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