node.js – 仅使用访问令牌使用Google API发送电子邮件

我想通过Google API发送电子邮件,而不需要不必要的OAUTH2参数.我只有该用户的access_token和refresh_token.

如何使用Request npm插件通过NodeJS中的基本POST请求通过Gmail API发送电子邮件?

最佳答案
亚伯拉罕是对的,但我以为我会举个例子.

var request = require('request');

server.listen(3000, function () {
  console.log('%s listening at %s', server.name, server.url);

  // Base64-encode the mail and make it URL-safe 
  // (replace all "+" with "-" and all "/" with "_")
  var encodedMail = new Buffer(
        "Content-Type: text/plain; charset=\"UTF-8\"\n" +
        "MIME-Version: 1.0\n" +
        "Content-Transfer-Encoding: 7bit\n" +
        "to: reciever@gmail.com\n" +
        "from: sender@gmail.com\n" +
        "subject: Subject Text\n\n" +

        "The actual message text goes here"
  ).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');

  request({
      method: "POST",
      uri: "https://www.googleapis.com/gmail/v1/users/me/messages/send",
      headers: {
        "Authorization": "Bearer 'access_token'",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        "raw": encodedMail
      })
    },
    function(err, response, body) {
      if(err){
        console.log(err); // Failure
      } else {
        console.log(body); // Success!
      }
    });
});

不要忘记更改接收方和发件人电子邮件地址以使示例正常工作.

转载注明原文:node.js – 仅使用访问令牌使用Google API发送电子邮件 - 代码日志