簡體   English   中英

使用Google API僅使用訪問令牌發送電子郵件

[英]Send email using Google API with only access token

我想通過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!
      }
    });
});

不要忘記更改接收方和發件人電子郵件地址以使示例正常工作。

將OAuth2 access_tokens附加到Google API請求有兩種方法

  • 使用access_token查詢參數,如下所示: ?access_token=oauth2-token
  • 像這樣使用HTTP Authorization標頭: Authorization: Bearer oauth2-token

第二個是首選POST請求,因此發送電子郵件的原始HTTP請求看起來像這樣。

POST /gmail/v1/users/me/messages/send HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer oauth2Token
{"raw":"encodedMessage"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM