Created
April 25, 2020 12:53
-
-
Save joshkadis/7bba701cf8e78d002ba8e4ca2f085f16 to your computer and use it in GitHub Desktop.
Gmail autoarchive by label
This file contains hidden or 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
// Will be checked against lowercased label names | |
var autoarchiveLabels = { | |
newsletters: 2 | |
}; | |
// Get cutoff date for a specific label | |
function labelDelayDate(labelName) { | |
if (!autoarchiveLabels[labelName.toLowerCase()]) { | |
return false; | |
} | |
var delayDays = autoarchiveLabels[labelName.toLowerCase()]; | |
var maxDate = new Date(); | |
maxDate.setDate(maxDate.getDate() - delayDays); | |
return maxDate; | |
} | |
// Archive thread after cutoff dat | |
function shouldArchive(thread, label) { | |
var maxDate = labelDelayDate(label.getName()); | |
if (!maxDate) { | |
return false; | |
} | |
// Being in the inbox already is implicit but helps with logging | |
// on the threads that are affected | |
var shouldArchive = thread.getLastMessageDate() < maxDate && thread.isInInbox(); | |
if (shouldArchive) { | |
Logger.log('Will archive: ' + thread.getFirstMessageSubject()); | |
} | |
return shouldArchive; | |
} | |
// Check threads against cutoff date and archive them | |
function archiveLabel(label) { | |
Logger.log('Archiving ' + label.getName()); | |
var threads = label.getThreads(0, 100).filter( | |
function (thread) { return shouldArchive(thread, label) } | |
); | |
Logger.log('Found ' + threads.length + ' archivable threads'); | |
if (threads.length) { | |
GmailApp.moveThreadsToArchive(threads); | |
} | |
} | |
// Loop through archivable labels | |
function gmailAutoarchive() { | |
var labels = GmailApp.getUserLabels(); | |
for (var i = 0; i < labels.length; i++) { | |
var label = labels[i]; | |
if (Object.keys(autoarchiveLabels).indexOf(label.getName().toLowerCase()) !== -1) { | |
archiveLabel(label); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment