-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGAS_Code
136 lines (112 loc) · 7.36 KB
/
GAS_Code
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
Must have Gmail advanced service enabled in Resources menu.
BEFORE YOU RUN THIS FIRST TIME: you must create a filter manually in gmail; the FROM line must have "[email protected]" in it. The action can be whatever you want - apply a label and archive; move to trash; whatever.
*/
function blocksenderDomains() {
console.log("************* Starting script. ***********");
const targetLabelName = '_block_domain'; // this is the label that I will manually apply in gmail, to a thread for which I want this script to block the sender's domain.
const completedLabelName = '_domain_blocked'; // this is the label the script will apply to show that the thread has been processed. (The target filter will be removed so that the script won't process it again)
var targetLabelObj = GmailApp.getUserLabelByName(targetLabelName);
var completedLabelObj = GmailApp.getUserLabelByName(completedLabelName);
try { // Wrap the entire function in a try / catch, in case there is an error, log it.
var tempThreadsArr = GmailApp.search("label:"+targetLabelName, 0, 10); // Get up to 10 threads that are marked
if (tempThreadsArr.length > 0) { // If there are threads
console.log("Found threads, count = " + tempThreadsArr.length);
var tempSenderDomains = "";
for (var t=tempThreadsArr.length-1; t>=0; t--) { // For each thread
var tempLabelsArr = tempThreadsArr[t].getLabels(); // Get the labels of the thread
for (var i in tempLabelsArr) { // For each label
if (tempLabelsArr[i].getName() == targetLabelName) { // If the label on the new thread matches the target filter name -- i.e. I've marked this thread for the script to act on it
var tempThreadObj = tempThreadsArr[t]; // Get the current thread we are iterating over
var tempMessage = tempThreadObj.getMessages()[0]; // Get the first message in the thread
var tempSender = tempMessage.getFrom(); // Get the sender's email address
console.log("Found message marked for blocking from sender: " + tempSender);
tempSenderDomains += " OR " + tempSender.substring(tempSender.indexOf("@"),tempSender.length-1); // works good.
console.log("Adding domain to blocked list: " + tempSenderDomains);
} // end of IF the label on the thread matches our target label
} // end of FOR each label on the thread
} // end of FOR each thread
// now I've gathered the sender's domain from every marked message, concatenated in tempSenderDomains. Time to add that list to the Filter.
var checkSuccessBln = updateAutoblockFilter(tempSenderDomains);
if (checkSuccessBln) {
console.log("Filter update returned success. Archiving the target threads.");
for (var i in tempThreadsArr) {
tempThreadObj = tempThreadsArr[i];
tempThreadObj.removeLabel(targetLabelObj); // don't want to process it again on next run
tempThreadObj.addLabel(completedLabelObj); // may want to see what threads have been dealt with
tempThreadObj.moveToArchive(); // move it out of inbox if it's there.
//tempThreadObj.moveToTrash();
} // end of tempThreadsArr loop
console.log("Archiving finished.");
} // end of IF updating filter was successful
else {
throw "Unknown error, updateAutoblockFilter returned false."
} // end of ELSE updating filter was successful
} // end of IF there are threads
else {
console.log("No target threads found. Ending work.");
}
} catch (e) {
Logger.log(e.toString());
} // end of catch()
console.log("************* Ending script. ***********");
} //end of fn Block Sender Domain
//*************************************************************************************************************************************
function updateAutoblockFilter(senderDomains) {
var tempScriptProperties = PropertiesService.getScriptProperties();
var tempFilterId = tempScriptProperties.getProperty("DomainBlockFilterID");
var autoBlockFilter
// find the autoBlockFilter using the ID:
if (tempFilterId) {
autoBlockFilter = Gmail.Users.Settings.Filters.get("me", tempFilterId) // if tempFilterId is null, Filters.get returns ALL of them in an array.
}
else {
}
if (autoBlockFilter) {
console.log("Found the autoblock filter by ID from script properties.");
var tempCrit = autoBlockFilter.getCriteria(); // this is ok
var tempFromString = tempCrit.getFrom(); // this throws error in work account but not in personal account...??
console.log("Filter ID: " + autoBlockFilter.id + " | FROM criteria: " + autoBlockFilter.getCriteria().getFrom() + "\nActions:\n" + autoBlockFilter.getAction());
} // end of IF autoblockfilter is populated
else {
// loop thru ALL existing filters, see if you can find the right one using the dummy email address in the FROM criteria.
var filtersList = Gmail.Users.Settings.Filters.list('me');
for (var i=0; i<filtersList.filter.length; i++) {
// SUBJ criteria: filtersList.filter[i].getCriteria().getSubject()
// https://developers.google.com/gmail/api/reference/rest/v1/users.settings.filters#Criteria
var tempFromString = "" + filtersList.filter[i].getCriteria().getFrom();
if (tempFromString.includes("[email protected]")) {
autoBlockFilter = filtersList.filter[i];
console.log("Found the autoblock filter by looping through all filters");
console.log("Filter ID: " + autoBlockFilter.id + " | FROM criteria: " + autoBlockFilter.getCriteria().getFrom() + "\nActions:\n" + autoBlockFilter.getAction());
break; // don't need to loop thru the rest of the filters list.
} // end of IF tempfromstring.includes
} // end of FOR loop through existing filters
} // end of ELSE, autoblockfilter wasn't found with the ID, so we needed to loop and find it.
// NOW need to test again - if the filter still wasn't found, throw error
if(autoBlockFilter) {
}
else {
throw "Autoblock filter not found by looping or by ID. Please create it manually."
}
console.log("Adding new domains to filter criteria.");
tempFromString = autoBlockFilter.getCriteria().getFrom();
tempFromString += senderDomains;
autoBlockFilter.criteria.from = tempFromString; // this only updates the local object, not the server.
// The API apparently has Create and Delete, but no way to UPDATE rules. Will have to delete it, and add new rule using the temp object.
console.log("Creating new filter.");
var newTempFilter = Gmail.Users.Settings.Filters.create(autoBlockFilter,'me');
// TEST to see if this succeeded! If it failed, then skip the Remove command.
if (newTempFilter) {
console.log("New filter ID is: " + newTempFilter.id);
console.log("Removing old filter.");
Gmail.Users.Settings.Filters.remove('me',autoBlockFilter.id); // yes, the new filter was created OK, so we can delete the old one.
var newProperties = {"DomainBlockFilterID":newTempFilter.id};
tempScriptProperties.setProperties(newProperties); // saves the new filter's ID to the script properties, overwriting the old value
}
else {
console.log("New filter failed to create, so I'm skipping the delete.")
throw "New filter failed to create, so I'm skipping the delete.";
}
return true;
} // end fn updateAutoblockFilter