Sending an email with Gmail's API using only a token?

谁说我不能喝 提交于 2019-12-06 11:53:26
Tholle

The access token you mentioned needs to be present in the POST-request you send the mail with. The Oauth2-procotol dictates that you need to either pass along a header Authorization: Bearer <ACCESS_TOKEN>, or a parameter access_token=<ACCESS_TOKEN>.

The value of raw also needs to be a valid base64-encoded rfc822 mail. An example in JavaScript could look like the following:

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

      "This is where the mail text will go"
    ).replace(/\+/g, '-').replace(/\//g, '_');

This will result in a string that you use as the raw in the request body.

A request in Postman would then look like the following:

POST https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token=<ACCESS_TOKEN>

{ // The encoded mail from the example above.
 "raw": "Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJVVEYtOCIKTUlNRS1WZXJzaW9uOiAxLjAKQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogN2JpdApTdWJqZWN0OiBTdWJqZWN0IG9mIHRoZSBtYWlsCkZyb206IHNlbmRlckBnbWFpbC5jb20KVG86IHJlY2lldmVyQGdtYWlsLmNvbQoKVGhpcyBpcyB3aGVyZSB0aGUgbWFpbCB0ZXh0IHdpbGwgZ28="
}

You also need to supply the Content-Type-header with the value of application/json. Note that you don't have to use a userId. Supplying me will make Google use the user associated with the supplied access token automatically.

Also make sure you asked for a sufficient permission scope with Passport. https://mail.google.com/ will work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!