Skip to content

Instantly share code, notes, and snippets.

@justinrfenn
Last active July 1, 2018 05:20
Show Gist options
  • Save justinrfenn/2dc01e9ad76b326ea7534885bf35f9ce to your computer and use it in GitHub Desktop.
Save justinrfenn/2dc01e9ad76b326ea7534885bf35f9ce to your computer and use it in GitHub Desktop.
Gmail script to archive any email thread older than a specified number of days
// Note: Due to the execution timeout google has on scripts, this will only archive 1000-3000 emails.
// If set as a project trigger with a reasonable frequency, you would only have to bulk archive emails once then the script will archive your emails without timing out.
function RunArchive() {
ArchiveMail(30);
}
function ArchiveMail(threadAgeThresholdDays) {
Logger.log('Archiving threads older than %s days ago', threadAgeThresholdDays);
var thresholdDate = new Date(new Date().setDate(new Date().getDate() - threadAgeThresholdDays));
var thresholdDateString = thresholdDate.getYear() + "/" + thresholdDate.getMonth() + "/" + thresholdDate.getDay();
var index = 0;
var batchSize = 100;
var searchResults = GmailApp.search('in:Inbox before:'+thresholdDateString, index, batchSize);
while(searchResults.length){
Logger.log('Archiving batch of %s...', batchSize);
GmailApp.moveThreadsToArchive(searchResults);
Logger.log(searchResults.length);
index += batchSize;
searchResults = GmailApp.search('in:Inbox before:'+thresholdDateString, index, batchSize);
}
Logger.log('Finished Archiving');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment