node.js - 使用仅具有访问 token 的 Google API 发送电子邮件

标签 node.js google-api gmail-api google-api-nodejs-client

我想在没有不必要的 OAUTH2 参数的情况下通过 Google API 发送电子邮件。我只有那个用户的 access_token 和 refresh_token。

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

最佳答案

abraham 是正确的,但我只是想给你举个例子。

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 - 使用仅具有访问 token 的 Google API 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29504289/

相关文章:

html - 为客户构建静态网站的最佳方式?

ios - 第二次登录 gmail 登录后不会启动帐户选择器

node.js - Gmail - smtp 错误 421 4.7.0

python - "Requested entity was not found."当管理员尝试修补另一个用户签名时

javascript - 为什么要使用 readFileAsync 来读取 Node.js 中包含 json 的文件?

javascript - Moment JS fromNow 对 map 中的所有日期返回相同的值 'A Year Ago'

PHP 执行 casperjs/phantomjs 脚本

android - 谷歌 API 的 SHA1

google-apps-script - 在 Google Apps 脚本中使用 GMail API 发送电子邮件

javascript - Uncaught ReferenceError : variableis not defined