我在尝试使用googleapis lib从node.js脚本访问GMail Google API时遇到了困难。我成功了一次,但我不记得我是怎么做到的,我试图重置Google项目后的项目,服务帐户和G-Suite Domain wide委托...
这是我做的:
在我的GCP控制台控制台中, 1.现有组织:lechorodescharentes.org 在这个组织中,我创建了一个项目:choro-dev 3.在这个项目中,我创建了一个服务帐户:choro-dev-postoffice 使用角色TokenGenerator的choro-dev-postoffice 并启用了Google Apps Domain-wid委派 下载了新的私钥(JSON文件) 4.我启用了GMail API(来自Libray菜单)
在我的G-Suite域管理控制台中, 5.我为此服务帐户的ClientID添加了以下内容 " https://www.googleapis.com/auth/admin.directory.user&#34 ;, " https://www.googleapis.com/auth/admin.directory.group"
Node.js客户端 我正在尝试使用node.js googleapis库使用以下Firebase功能代码访问GMail API 使用服务帐户进行服务器身份验证 请参阅node.js客户端代码 在这段代码中,我有2个身份验证功能 connect():到JSON Web令牌 authorize():从Google OAuth 2.0授权服务器
部署了Firebase功能
node.js客户端代码
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const {google} = require('googleapis');
const nodemailer = require('nodemailer')
const _ = require('lodash');
const KEY = require('./service-key.json');
function connect () {
return new Promise((resolve, reject) => {
const jwtClient = new google.auth.JWT(
KEY.client_email,
null,
KEY.private_key,
_.values(KEY.scopes), // scopes as authorized in G-Suite admin
KEY.admin_email . // impersonated user
);
jwtClient.authorize((err) => {
if(err) {
reject(err);
} else {
resolve(jwtClient); // returns client
}
});
});
}
// Send a message to the contact user
function sendMessage (client, sender, msg) {
return new Promise((resolve, reject) => {
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: KEY.admin_email,
serviceClient: KEY.client_id,
privateKey: KEY.private_key,
accessToken: client.access_token,
refreshToken: client.refresh_token,
expires: client.expiry_date
}
});
const mailOptions = {
from: 'SITE CONTACT<' + sender + '>',
to: KEY.contact_email,
subject: 'Message',
text: 'From: ' + sender + '\n\n' + msg,
html: '<h1>Message</h1><p>From: ' + sender + '</p><p>' + msg + '</p>'
};
transporter.sendMail(mailOptions, (err, response) => {
if (err) {
reject(err);
return;
}
resolve(response);
});
});
}
function newContactMessage (from, msg) {
return connect()
.then(client => {
return sendMessage(client, from, msg);
});
}
exports.sendContactMessage = functions.https.onRequest((req, res) => {
const sender_email = 'dufourisabelle@orange.fr';
const sender_msg = 'just a test message to contact the site owner.'
newContactMessage(sender_email, sender_msg).then(() => {
return {status: 200};
}, error => {
return {status: error.status, infos: error.message};
}).then(response => {
return res.send(response);
}).catch(console.error);
});
我可以添加什么?我会尝试重新启动所有过程并祈祷...... ??