How to edit Gmail messages as they arrive?

你离开我真会死。 提交于 2019-12-03 20:31:13
Tholle

I think the Gmail API would suit your needs perfectly.

Let's say I'm polling my Inbox every minute for new messages, with the Users.messages.list()-request. I'm careful to use the after-parameter in my query with the value of the last time I checked my Inbox, as seconds since the epoch. I only ask for Ids of the potential new messages. You could also subscribe to push events to mitigate the risk of your user pressing the message before you poll and alter the messages, as mentioned by @Max in the comments. Probably not an issue if the script is just for you.

q = after:<TIME_IN_SECONDS_SINCE_EPOCH_OF_LAST_POLL>
fields = messages/id

GET https://www.googleapis.com/gmail/v1/users/me/messages?fields=messages%2Fid&q=after%3A1437677475478&access_token={YOUR_API_KEY}

Response:

{
 "messages": [
    {
     "id": "14ebc16800d1fdc0"
    }, ...
  ]
}

Ha! I have a new message. I get it raw, decode its URL safe base64-encoded content, and have a look.

format = raw
fields = raw

GET https://www.googleapis.com/gmail/v1/users/me/messages/14eb68cb028163ba?fields=raw&format=raw&access_token={YOUR_API_KEY}

Response:

{
 "raw": "RGVsaXZlcmVk..."
}

Let's do the aforementioned base64-decoding. Replace all the "-" with "+", and "_" with "/" to transform it from URL safe base64 data to regular base64-encoded data.

atob("RGVsaXZlcmVk...".replace(/\-/g, '+').replace(/\_/g, '/'));

Result:

<html lang="en">
<head>
<title>
Computerphile just uploaded a video
</title>

.
.
.


<img class="open_tracking_img" src="http://www.youtube.com/attribution_link?a=vi-KC3YA0Qc&u=/gen_204%3Fa%3Dem-uploademail" width="1" height="1">

.
.
.
</html>

Contains a lot of img-tags, for sure.

I just extract the img-tags, get the URLs, and remove all the img-tags in the mail with my favourite XML Parser.

After the tags are removed, I just insert the URLs in the mail where I see fit, and encode it back to the URL safe base64-encoded data it was retrieved in.

btoa("<html lang="en">...".replace(/\+/g, '-').replace(/\//g, '_'));

Finally, I delete the original mail and insert the modified one.

DELETE https://www.googleapis.com/gmail/v1/users/me/messages/14eb68cb028163ba?access_token={YOUR_API_KEY}

POST https://www.googleapis.com/gmail/v1/users/me/messages?access_token={YOUR_API_KEY}

{
 "raw": "RGVsaXZlcmVkLVRvO..."
}

My new, modified mail is now in the inbox instead!

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