Node.js向Gmail API发送消息的POST请求

我正尝试使用服务器端node.js向Gmail Send Message API发送请求,但没有成功。 我收到以下错误:

body: '{ "error": { "errors": [ { "domain": "global", "reason": "invalidArgument", "message": "\'raw\' RFC822 payload message string or uploading message via /upload/ URL required" } ], "code": 400, "message": "\'raw\' RFC822 payload message string or uploading message via /upload/ URL required" } }' } 

oauth2token和raw的input参数是有效的,事实上,如果我使用Google OAuth 2操场( https://developers.google.com/oauthplayground )并使用令牌和raw作为电子邮件发送的值。 有人可以看到我错过了什么吗?

  function sendMail(oauth2token, raw) { context.log('Token: ' + oauth2token); context.log('raw: ' + raw); var params = { userId: user_id, resource: { 'raw': raw} }; var headers = { "HTTP-Version": "HTTP/1.1", "Content-Type": "application/json", "Authorization": "Bearer " + oauth2token }; var options = { headers: headers, url: "https://www.googleapis.com/gmail/v1/users/me/messages/send", method: "POST", params: params }; request(options, function (error, response, body) { if (!error && response.statusCode == 200) { context.log(body); } if (error) { context.log(error); } else { context.log(response); } }) } 

如果您在Google操场上进行testing并且看起来不错,我会开始查看您正在使用的其他外部依赖项。 例如,请求。 也许你需要传递一个parsing的url对象而不是url。 看看这个: https : //github.com/request/request#requestoptions-callback 。

这里是你parsing的url对象的样子:

 Url { protocol: 'https:', slashes: true, auth: null, host: 'www.googleapis.com', port: null, hostname: 'www.googleapis.com', hash: null, search: null, query: null, pathname: '/gmail/v1/users/me/messages/send', path: '/gmail/v1/users/me/messages/send', href: 'https://www.googleapis.com/gmail/v1/users/me/messages/send' } 

要么或者改变你现有的select,而不是url

你只需要传递正文中的raw消息:

 function sendMail (oauth2token, raw) { var options = { method: 'POST', url: 'https://www.googleapis.com/gmail/v1/users/me/messages/send', headers: { 'HTTP-Version': 'HTTP/1.1', 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + oauth2token }, body: JSON.stringify({ raw: raw }) }; request(options, function (error, response, body) { if (!error && response.statusCode == 200) { context.log(body); } if (error) { context.log(error); } else { context.log(response); } }); }