-
-
Save Rohaq/9641276b277cb2a8b3a3569e4193d4a4 to your computer and use it in GitHub Desktop.
Autoarchive Gmail script for Google Scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function gmailAutoarchive() { | |
let labelRules = { | |
"Autoarchive": [ | |
{ "days": 60, "actions": ["archive", "markread"] } | |
], | |
"Autodelete": [ | |
{ "days": 60, "actions": ["delete"] } | |
], | |
"Label 1": [ | |
{ "days": 30, "actions": ["archive", "markread"] } | |
], | |
"Label 2": [ | |
{ "days": 90, "actions": ["archive", "markread"] } | |
], | |
"Label 3": [ | |
{ "days": 60, "actions": ["archive", "markread"] } | |
], | |
"Label 4": [ | |
{ "days": 14, "actions": ["archive", "markread"] }, | |
{ "days": 30, "actions": ["delete"] } | |
], | |
"Label 5": [ | |
{ "days": 14, "actions": ["archive", "markread"] } | |
] | |
}; | |
Object.keys(labelRules).forEach((label) => { | |
console.log("Processing Label: " + label); | |
let labelObj = GmailApp.getUserLabelByName(label); | |
// Skip over label if it's not found... | |
if (labelObj == null) { | |
console.log("Label " + label + " does not exist, moving on..."); | |
return; | |
} | |
let threads = labelObj.getThreads(0, 400); | |
let rules = labelRules[label]; | |
// Counters | |
let processed = 0; | |
let archived = 0; | |
let markedread = 0; | |
let deleted = 0; | |
rules.forEach((actionSet) => { | |
let maxDate = new Date(); | |
maxDate.setDate(maxDate.getDate() - actionSet.days); // What was the date at that time? | |
// Process threads if they're older than the limit we set, and don't have starred messages. | |
threads.forEach((thread) => { | |
if (thread.getLastMessageDate() < maxDate && !thread.hasStarredMessages() | |
) { | |
if (actionSet.actions.indexOf("archive") != -1 && thread.isInInbox()) { | |
console.log("Archiving: " + thread.getFirstMessageSubject() + " [" + thread.getLastMessageDate().toDateString() + "]"); | |
thread.moveToArchive(); | |
archived++; | |
} | |
if (actionSet.actions.indexOf("markread") != -1 && thread.isUnread()) { | |
console.log("Marking Read: " + thread.getFirstMessageSubject() + " [" + thread.getLastMessageDate().toDateString() + "]"); | |
thread.markRead(); | |
markedread++; | |
} | |
if (actionSet.actions.indexOf("delete") != -1 && !thread.isInTrash()) { | |
console.log("Deleting: " + thread.getFirstMessageSubject() + " [" + thread.getLastMessageDate().toDateString() + "]"); | |
thread.moveToTrash(); | |
deleted++; | |
} | |
processed++; | |
} | |
}); | |
}); | |
console.log(processed + " threads processed for label " + label + ". [" + archived + " archived, " + markedread + " marked read, " + deleted + " deleted]"); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment