Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Original author fwed (contact@fwed.fr)
// Modified from
// https://gist.github.com/0x4a/e410aa72fca06fcfafce9f00ff47d82c
// https://gist.github.com/anonymous/2cca33d376f7f924fdaa67891ad098cc
// https://medium.com/@fw3d/auto-archive-emails-in-gmail-after-2-days-1ebf0e076b1c
var OP_ARCHIVE = 1;
var OP_READ = 2;
var OP_DELETE = 4;
var ONE_MONTH = "1m";
var THREE_MONTHS = "3m";
function gmailAutocleanup() {
gmailBatchArchive("label:foo", ONE_MONTH, THREE_MONTHS);
gmailBatchArchive("label:bar", "3d", THREE_MONTHS);
gmailBatchOp("from:spammy", "3d", null, OP_READ | OP_ARCHIVE);
}
/**
* Archive threads
*/
function gmailBatchArchive(search, older_than, newer_than) {
gmailBatchOp(search, older_than, newer_than, OP_ARCHIVE);
}
/**
* Batch process gmail threads with one or more operations given by op
*
* @param search Search string to filter messages (e.g., by label or from)
* @param older_than Filter messages older than this timeframe (e.g., 2d [days], 1m [month])
* @param newer_than Optionally filter messages newer than this timeframe
* @param op Bitmask flag of operations to perform (OP_ARCHIVE, OP_READ, OP_DELETE)
*/
function gmailBatchOp(search, older_than, newer_than, op) {
var string = search + " in:inbox -in:starred older_than:" + older_than;
if (newer_than) {
string += " newer_than:" + newer_than;
}
var ops = "";
if (op & OP_ARCHIVE) ops += "archive";
if (op & OP_READ) ops += "; mark_read";
if (op & OP_DELETE) ops += "; delete";
Logger.log("running gmail batch ops: " + ops);
Logger.log("search string: " + string);
var threads = GmailApp.search(string, 0, 500);
var num = threads.length;
Logger.log("found: " + num + " threads older than " + older_than);
if (num === 0) {
return;
}
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);
if (op & OP_ARCHIVE) {
GmailApp.moveThreadsToArchive(this_batch);
}
if (op & OP_READ) {
GmailApp.markThreadsRead(this_batch);
}
if (op & OP_DELETE) {
GmailApp.moveThreadsToTrash(this_batch);
}
}
Logger.log("finished processing " + num + " threads\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.