Skip to content

Instantly share code, notes, and snippets.

@sorja
Created October 15, 2018 03:54
Show Gist options
  • Save sorja/5b34aa9c56771acd9b82e1ae4fa32757 to your computer and use it in GitHub Desktop.
Save sorja/5b34aa9c56771acd9b82e1ae4fa32757 to your computer and use it in GitHub Desktop.
Automatic archiving of Gmail's emails which are labeled with 'autoarchive' or 'autoarchiveX' where 0 < X < 10.
function gmailAutoarchive() {
// Get all the labels
var labels = GmailApp.getUserLabels();
// Filter out the ones not containinig autoarchive
var autoarchive = labels.filter(function (label) {
var labelName = label.getName();
return labelName.indexOf("autoarchive") !== -1;
});
//helper function to archive threads given to it
function archiveThreads(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);
}
}
// helper function to extract the last number, otherwise return 1
// This allows you to have different autoarchive labels in gmail,
// for example autoarchive, autoarchive4, autoarchive8.
// Limit is 1 digit number.
function getNumberFromLabel(label) {
if (label == null || label == undefined) {
return 1
}
// Get name returns String representation of the label
var n = label.getName().slice(-1);
var delayDays = 1;
// If it's just autoarchive for example,
// we can skip
if (!isNaN(n)) {
delayDays = Number(n);
}
return delayDays
}
// Main loop, autoarchive contains all labels that have
// the keyword "autoarchive" in it. We loop through it and
// handle each labels' threads.
for (var i = 0 ; i < autoarchive.length ; i++) {
var label = autoarchive[i];
//--> ex. autoarchive3
var query = "in:inbox label:autoarchive older_than:" + getNumberFromLabel(label) + "d"
// Use Googles own api to search the above query.
var threads = GmailApp.search(query);
// Archive the threads
archiveThreads(threads)
}
@sorja
Copy link
Author

sorja commented Oct 15, 2018

Modification allows to have different autoarchivement labels for specific amount of day/s.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment