Skip to content

Instantly share code, notes, and snippets.

@saagarjha
Created October 20, 2016 02:04
Show Gist options
  • Save saagarjha/d8657a5cee921856186cd12180ae675a to your computer and use it in GitHub Desktop.
Save saagarjha/d8657a5cee921856186cd12180ae675a to your computer and use it in GitHub Desktop.
Google Apps Script to archive old emails in a label
function shouldStop(startTime) {
return new Date().getTime() - startTime.getTime() > 300000; // 5 minutes
}
function archive() {
var days = 7; // How old a message must be to be archived
var startTime = new Date();
var date = new Date();
date.setDate(date.getDate() - days);
var label = GmailApp.getUserLabelByName("[LABEL NAME]");
var threads = label.getThreads().filter(function (thread) {
return !thread.isUnread() && thread.getLastMessageDate() < date;
});
var oldUnreadThreads = [];
for (var i = 0; i < threads.length; i++) {
var thread = threads[i];
Logger.log(thread.getFirstMessageSubject());
Logger.log(thread.getLastMessageDate());
oldUnreadThreads.push(thread);
}
for (var i = 0; i < oldUnreadThreads.length / 100; i++) {
if (shouldStop(startTime)) {
Logger.log("Reached time limit, processed approximately" + i * 100 + " / " + threads.length + "threads");
break;
}
GmailApp.moveThreadsToArchive(oldUnreadThreads.slice(i * 100, i * 100 + 99));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment