Gmail API send message without using Base64 encode

本秂侑毒 提交于 2021-02-19 07:37:53

问题


I am using this interface: https://developers.google.com/gmail/api/v1/reference/users/messages/send#examples

I was testing API request from the form on the website. It requires raw Base64 encoded string such as:

TUlNRS1WZXJzaW9uOiAxLjANClJlY2VpdmVkOiBieSAxMC4xOTQuNjguMjI3IHdpdGggSFRUUDsgV2VkLCAyNCBBdWcgMjAxNiAwMjo1OToxNyAtMDcwMCAoUERUKQ0KRGF0ZTogV2VkLCAyNCBBdWcgMjAxNiAxMTo1OToxNyArMDIwMA0KRGVsaXZlcmVkLVRvOiBrcnVub0B1bGl4dHJhdmVsLmNvbQ0KTWVzc2FnZS1JRDogPENBSzB5QmZZeEgwS1dGbng2TzNfZ3ZNRkxtVlB5RVY9NjdnQW5qRWdPaHIzSGZOTkJCUUBtYWlsLmdtYWlsLmNvbT4NClN1YmplY3Q6IFRoaXMgaXMgYSBzdWJqZWN0DQpGcm9tOiBLcnVub3NsYXYgVUxJWFRyYXZlbCA8a3J1bm9AdWxpeHRyYXZlbC5jb20-DQpUbzogS3J1bm9zbGF2IEJhbm92YWMgPGt1bm9rZGV2QGdtYWlsLmNvbT4NCkNvbnRlbnQtVHlwZTogbXVsdGlwYXJ0L2FsdGVybmF0aXZlOyBib3VuZGFyeT0wNDdkN2JhZTQ5NjRhMmQ3MzAwNTNhY2U1NWUxDQoNCi0tMDQ3ZDdiYWU0OTY0YTJkNzMwMDUzYWNlNTVlMQ0KQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PVVURi04DQoNClRoaXMgaXMgYSBib2R5DQoNCi0tMDQ3ZDdiYWU0OTY0YTJkNzMwMDUzYWNlNTVlMQ0KQ29udGVudC1UeXBlOiB0ZXh0L2h0bWw7IGNoYXJzZXQ9VVRGLTgNCg0KPGRpdiBkaXI9Imx0ciI-VGhpcyBpcyBhIGJvZHk8YnI-PC9kaXY-DQoNCi0tMDQ3ZDdiYWU0OTY0YTJkNzMwMDUzYWNlNTVlMS0t

How do I instead use basic parameters (such as subject, sender, reciver, message body) to send mail?


回答1:


You first build the message with headers likeFrom and Subject as you mentioned, but you have to encode the message before sending it. There is no way around that.

The following is an example in JavaScript, with the use of JQuery:

// Base64-encode the mail and make it URL-safe 
// (replace all "+" with "-" and all "/" with "_")
var encodedMessage = btoa([
  "From: sender@gmail.com\r\n",
  "To: reciever@gmail.com\r\n",
  "Subject: Subject of the message\r\n\r\n",

  "This is the text of the message"
].join("")).replace(/\+/g, '-').replace(/\//g, '_');

$.ajax({
  method: "POST",
  url: "https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token={access_token}",
  contentType: "application/json",
  data: JSON.stringify({           
    raw: encodedMessage
  })
});


来源:https://stackoverflow.com/questions/39120416/gmail-api-send-message-without-using-base64-encode

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