简体   繁体   English

使用Google API仅使用访问令牌发送电子邮件

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

I want to send an email through Google API without the unnecessary OAUTH2 parameters. 我想通过Google API发送电子邮件,而不需要不必要的OAUTH2参数。 I only have the access_token and the refresh_token of that user. 我只有该用户的access_token和refresh_token。

How can I send an email through Gmail API through a basic POST request in NodeJS, with Request npm plugin? 如何使用Request npm插件通过NodeJS中的基本POST请求通过Gmail API发送电子邮件?

abraham is correct, but I just thought I'd give you an example. 亚伯拉罕是对的,但我以为我会举个例子。

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!
      }
    });
});

Don't forget to change the reciever and sender email address for the example to work. 不要忘记更改接收方和发件人电子邮件地址以使示例正常工作。

There are two methods for attaching OAuth2 access_tokens to a Google API request. 将OAuth2 access_tokens附加到Google API请求有两种方法

  • Using the access_token query parameter like this: ?access_token=oauth2-token 使用access_token查询参数,如下所示: ?access_token=oauth2-token
  • Using the HTTP Authorization header like this: Authorization: Bearer oauth2-token 像这样使用HTTP Authorization标头: Authorization: Bearer oauth2-token

The second one is prefered for POST requests so the raw HTTP request for sending an email would look something like this. 第二个是首选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