/
autoForwardMail.gs
70 lines (57 loc) · 2.57 KB
/
autoForwardMail.gs
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
function autoForwardMail() {
// Define the developer flag
var developerMode = false; // Set this to false when you want the script to execute actions
var archiveWhenDone = false; // Set this to true when you want the script to archive the thead after completing the actions, can be good to keep in the inbox, to visually inspect the action
// Replace these and enclose in ""
var forwardingAddress = <forwarToThisAddress@example.com>
var fromAddress = <myRmailAddress@example.com>
var todoLabelName = <auto-forward/todo>
var completedLabelName = <auto-forward/forward-complete>
// Define labels
var todoLabel = GmailApp.getUserLabelByName(todoLabelName) ?? GmailApp.createLabel(todoLabelName);
var forwardCompleteLabel = GmailApp.getUserLabelByName(completedLabelName) ?? GmailApp.createLabel(completedLabelName);
if (developerMode) {
// Log that the script was executed in developer mode
Logger.log("-- Executing in Developer Mode. No real actions will be taken.");
} else {
Logger.log("-- Executing in Production Mode");
}
todoLabel.getThreads().forEach(function(thread) {
Logger.log("\n" + "Thread: With first message subject '" + thread.getFirstMessageSubject() + "'");
var messages = thread.getMessages();
messages.forEach(function(message) {
var sender = message.getFrom();
var subject = message.getSubject();
Logger.log(" Message: From " + sender + " with subject '" + subject + "'");
if (!developerMode) {
// Forward the email to both recipient and self
message.forward(forwardingAddress, {
from: fromAddress,
subject: subject,
body: message.getBody(),
});
}
Logger.log(" Message: Forwarded to " + forwardingAddress);
if (!developerMode) {
// Mark the message as read
message.markRead();
}
Logger.log(" Message: Marked as read");
});
// Relabel as complete
if (!developerMode) thread.removeLabel(todoLabel);
Logger.log("Thread: Removed label '" + todoLabel.getName() + "'");
if (!developerMode) thread.addLabel(forwardCompleteLabel);
Logger.log("Thread: Added label '" + forwardCompleteLabel.getName() + "'");
if (archiveWhenDone) {
if (!developerMode) thread.moveToArchive();
Logger.log("Thread: Archived");
}
});
if (developerMode) {
// Log that the script was executed in developer mode
Logger.log("-- Executed in Developer Mode. No real actions were taken.");
} else {
Logger.log("-- Executed in Production Mode. All actions were taken.");
}
}