Skip to content

Instantly share code, notes, and snippets.

@auxesis
Created October 16, 2022 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save auxesis/e98247358ad8deec4b51680816620cd0 to your computer and use it in GitHub Desktop.
Save auxesis/e98247358ad8deec4b51680816620cd0 to your computer and use it in GitHub Desktop.
//
// Housekeeping script to trim Gmail Inbox.
//
// Automatically archives threads in inbox older than n days.
// Useful for cleaning up threads I forget to archive.
//
// Requires authorization to run.
// Google will occasionally prompt to remove permissions, warning "this app has access to everything" and "it is not trusted".
// If you do remove the authorization, running the script here should prompt for re-authorization.
function gmailAutoArchive() {
var threads = [
getThreads({ label: 'Weeklies', days: 7 }),
getThreads({ label: 'Dailies', days: 2 }),
getThreads({ label: 'Linkedin-Invitations', days: 2 }),
getThreads({ label: 'Domains', days: 3 }),
getThreads({ label: 'shopping-orders', days: 2 }),
getThreads({ label: 'Mouth-Hats', days: 3 }),
getThreads({ label: 'Banking', days: 2 }),
getThreads({ label: 'Meetup-Others', days: 3 }),
getThreads({ label: 'Meetup', days: 2 }),
getThreads({ label: 'Greens', days: 2 }),
].flat()
// archive all matching threads
archiveInBatches(threads);
}
function getThreads(m) {
var delayDays = m.days;
var maxDate = new Date();
maxDate.setDate(maxDate.getDate()-delayDays);
var label = m.label;
var query = `in:inbox label:${label}`;
var start = 0;
var max = 200;
var threads = GmailApp.search(query, start, max).filter(function(thread) {
// Only include threads older than the limit we set in delayDays
return (thread.getLastMessageDate() < maxDate);
});
return threads
}
function archiveInBatches(threads) {
var batch_size = 100;
while (threads.length) {
var this_batch_size = Math.min(threads.length, batch_size);
var 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