-
Notifications
You must be signed in to change notification settings - Fork 0
/
action.gs.js
77 lines (60 loc) · 1.95 KB
/
action.gs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Made by Camilo Castro <[email protected]>
// July 2020
// Use this in a Google Apps Script https://script.google.com
// Configure Access to Gmail API first
// https://developers.google.com/apps-script/guides/services/advanced#enabling_advanced_services
// Have a sane max of items to process.
const MAX_THREADS = 30;
const HTTP_ENDPOINT = "http://example.com/save-emails-endpoint";
// This token should be generated
// and stored in server and client
// use: make token
// to get a new uuid
const HTTP_AUTH_TOKEN = "8D271224-9A7C-4AC2-8C11-E7E7443C9DAB";
// Create a new filter in gmail to assign labels to new email messages
const LABEL_NAME = "my-label";
const processEmails = () => {
const sendDetailsToServer = (data) => {
const url =
`${HTTP_ENDPOINT}?token=${HTTP_AUTH_TOKEN}&json=` +
encodeURIComponent(JSON.stringify(data));
Logger.log("Calling", url);
const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
Logger.log(response);
return response;
};
const getMessages = () => {
const label = GmailApp.getUserLabelByName(LABEL_NAME);
if (!label) {
Logger.log("No label named", LABEL_NAME);
return [];
}
const threads = GmailApp.search(
`is:unread label:"${LABEL_NAME}"`,
0,
MAX_THREADS
);
Logger.log(threads.length, "Threads found");
const emails = [];
for (const thread of threads) {
const messages = thread.getMessages();
for (const message of messages) {
if (message.isUnread()) {
const email = {
subject: message.getSubject(),
body: message.getPlainBody(),
from: message.getFrom(),
date: message.getDate(),
};
emails.push({ email, message });
}
}
}
return emails;
};
const messages = getMessages();
for (const message of messages) {
sendDetailsToServer(message.email);
GmailApp.markMessageRead(message.message);
}
};