Skip to content

Instantly share code, notes, and snippets.

@orymate
Created October 12, 2023 15:18
Show Gist options
  • Save orymate/4ee5ab0cb3495ebbe598555ed0d1fe22 to your computer and use it in GitHub Desktop.
Save orymate/4ee5ab0cb3495ebbe598555ed0d1fe22 to your computer and use it in GitHub Desktop.
archive mails based on labels and time spent in inbox
function parseInterval(s) {
var matches = new RegExp("^expire-([0-9]+)([mhdDwM])$").exec(s);
if (!matches) {
return null;
}
var count = parseInt(matches[1]);
var unit = matches[2];
var date = new Date();
switch (unit) {
case "M":
date.setMonth(date.getMonth() - count);
break;
case "w":
date.setDate(date.getDate() - 7 * count);
break;
case "D": // working days
while (count > 0) {
date.setDate(date.getDate() - 1);
if (date.getDay() - 1 % 7 < 6) {
count--;
}
}
break;
case "d":
date.setDate(date.getDate() - count);
break;
case "h":
date.setHours(date.getHours() - count);
break;
case "m":
date.setMinutes(date.getMinutes() - count);
break;
default:
date = null;
}
return date;
}
function myFunction() {
var expired = GmailApp.createLabel("expired");
var labels = GmailApp.getUserLabels();
for (var label of labels) {
var name = label.getName();
var expire_at = parseInterval(name);
if (!expire_at) {
//Logger.log("Ignoring label: %s", name);
continue;
}
var threads = label.getThreads();
//var msg = threads[0];
for (var msg of threads) {
if (msg.getLastMessageDate() > expire_at) {
continue;
}
msg.moveToArchive();
msg.removeLabel(label);
msg.addLabel(expired);
Logger.log("Archived msg: %s (%s)", msg.getFirstMessageSubject(), msg.getLastMessageDate());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment