所以我离解决方案只有一步之遥,问题是在创建
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');
总之,正确的步骤是:
-
在Google云平台中创建项目
-
已创建服务帐户
-
启用
Domain Wide Delegation
服务帐户的
-
已下载JSON格式的服务帐户密钥
-
API Manager
>
Credentials
我创造了
OAuth 2.0 Client ID
-
已为项目启用Gmail API
在Google Apps管理控制台中:
-
在里面
Security
>
Advanced Settings
>
Manage API client access
我已经添加了
Client ID
从上面的步骤4开始
-
我已经为添加了所有可能的作用域
客户端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);
}
});
希望对别人有所帮助