Skip to content

Instantly share code, notes, and snippets.

@gajeam
Created July 27, 2021 15:04
Show Gist options
  • Save gajeam/7d0fc51f7bd92e952dfa3972835fc32a to your computer and use it in GitHub Desktop.
Save gajeam/7d0fc51f7bd92e952dfa3972835fc32a to your computer and use it in GitHub Desktop.
Auto archive
/*
Shout out to Gabe Benjiman from Github for the basis of this script
https://gist.github.com/GabeBenjamin/3ef20889fa37ae97e9492e58e90db892
For info on how to get this to run automatically in your email, check out this Medium post:
https://medium.com/@fw3d/auto-archive-emails-in-gmail-after-2-days-1ebf0e076b1c
*/
function gmailAutoArchive() {
// In a world where I am less lazy, this could be written better with a regex
const maxDays = 14;
for (var i = 1; i <= maxDays; i++) {
_gmailAutoarchiveHelper(i);
}
}
function _gmailAutoarchiveHelper(numDays) {
Logger.log('Running archiver for numDays: %s', numDays);
const delayDays = numDays; // will only impact emails more than numDays days
const maxDate = new Date();
maxDate.setDate(maxDate.getDate() - delayDays); // what was the date at that time?
// Get all the threads labeled 'autoarchive'
const labelName = "autoarchive-" + numDays + "d"
const label = GmailApp.getUserLabelByName(labelName);
if (label == null || label == undefined) {
Logger.log('Not found label with name %s', labelName)
return -1
}
Logger.log('Found label: %s', label.getName());
// If we have more than 500 emails with the tag, they won't all archive
const threads = label.getThreads(0, 500).filter(function(thread) {
// Only include threads older than the limit we set in delayDays
return (thread.getLastMessageDate() < maxDate && thread.isInInbox());
});
Logger.log('Found %s emails.', threads.length);
const batch_size = 100;
while (threads.length) {
const this_batch_size = Math.min(threads.length, batch_size);
const this_batch = threads.splice(0, this_batch_size);
GmailApp.moveThreadsToArchive(this_batch);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment