用于在Node.js中发送邮件的Gmail API

免责声明:

  • 我遵循Google自己的Node.js快速入门指南,并成功连接并使用gmail.users.labels.list()function。
  • 我已经在这里检查了这个问题/答案,就像这个 (不是使用Node.js API),或者这个 (类似于这个 )显然是我有同样的问题,但解决scheme不工作。

我的问题:

当使用Google的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函数来自我上面提到的Google指南。 它读取具有我的access_tokenrefresh_token .json文件。 makeBody函数是一个编码身体信息。

在configurationvariabels我也有:

 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()方法。
  • 我正在testing的邮件正文是否在Google的testing页上进行testing 。

我的问题:

我的设置错了吗? API有没有变化? 我错过了什么?

好的,所以我find了问题。

问题1遵循Node.js快速入门指南中的例子

 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 } 

那些生成的令牌考虑教程代码中的auth/gmail.readonly作用域。

所以我删除了第一个.json ,从我的最后一个作用域数组中添加了作用域(我发布了问题),并再次运行了教程安装程序,接收到一个新的标记。

问题#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); });