免责声明:
- 我关注的是谷歌自己的Node.js quickstart guide并成功连接并使用
gmail.users.labels.list()
功能。 - 我在这里查看了问题/答案,例如 this one (这不是使用我所询问的 Node.js API),或 this one (类似于 this one )这显然是我遇到的相同问题,但解决方案不起作用。
我的问题:
使用 Google's Node.js API 时我在尝试发送电子邮件时遇到错误。错误是:
{
"code": 403,
"errors": [{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}]
}
我的设置:
fs.readFile(secretlocation, function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
authorize(JSON.parse(content), sendMessage);
});
function sendMessage(auth) {
var raw = makeBody('myrealmail@gmail.com', 'myrealmail@gmail.com', 'subject', 'message test');
gmail.users.messages.send({
auth: auth,
userId: 'me',
message: {
raw: raw
}
}, function(err, response) {
res.send(err || response)
});
}
函数 processClientSecrets
来 self 上面提到的谷歌指南。它读取我的 .json
文件,其中包含我的 access_token
和 refresh_token
。 makeBody
function是一个编码的正文消息。
在配置变量中我也有:
var SCOPES = [
'https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.send'
];
为什么它应该起作用:
- 授权过程适用于
gmail.users.labels.list()
方法。 - 如果我在 Google's test page 进行测试,我正在测试的消息正文可以正常工作.
我的问题:
我的设置错了吗? API有变化吗?我错过了什么?
最佳答案
好的,所以我找到了问题。
问题 #1 在关注 Node.js quickstart guide 时该教程中的示例有
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
当我得到 .json
时,它看起来像:
{
"access_token": "xxx_a_long_secret_string_i_hided_xxx",
"token_type": "Bearer",
"refresh_token": "xxx_a_token_i_hided_xxx",
"expiry_date": 1451721044161
}
那些生成的 token 考虑到仅教程代码中的 auth/gmail.readonly
范围。
所以我删除了第一个 .json
,从我的最终范围数组中添加了范围(我在问题中发布)并再次运行教程设置,收到一个新 token 。
问题 #2
在传递给我发送的 API 的对象中:
{
auth: auth,
userId: 'me',
message: {
raw: raw
}
}
但那是错误的,message
键应该被称为resource
。
最终设置:
这是我添加到教程代码中的内容:
function makeBody(to, from, subject, message) {
var str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
"MIME-Version: 1.0\n",
"Content-Transfer-Encoding: 7bit\n",
"to: ", to, "\n",
"from: ", from, "\n",
"subject: ", subject, "\n\n",
message
].join('');
var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
}
function sendMessage(auth) {
var raw = makeBody('myrealemail@gmail.com', 'myrealemail@gmail.com', 'test subject', 'test message');
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: raw
}
}, function(err, response) {
res.send(err || response)
});
}
然后调用所有内容:
fs.readFile(secretlocation, function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Gmail API.
authorize(JSON.parse(content), sendMessage);
});
关于node.js - 用于在 Node.js 中发送邮件的 Gmail API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546142/