Skip to content

Instantly share code, notes, and snippets.

@strongriley
Last active February 23, 2019 16:04
Show Gist options
  • Save strongriley/48e50198340410ee979f0e79fe050c60 to your computer and use it in GitHub Desktop.
Save strongriley/48e50198340410ee979f0e79fe050c60 to your computer and use it in GitHub Desktop.
Auto Archive Email
// Auto-archive email older than X days (so long as not starred)
// Inspirations:
// - https://gist.github.com/anonymous/2cca33d376f7f924fdaa67891ad098cc
// - https://medium.com/@fw3d/auto-archive-emails-in-gmail-after-2-days-1ebf0e076b1c
// NOTE: Must have autoarchive and ttl1 labels already created to use.
var MAX_AGE_DAYS = 14;
var BEFORE_DATE = new Date();
BEFORE_DATE.setDate(BEFORE_DATE.getDate() - MAX_AGE_DAYS); // what was the date at that time?
var LABEL_NAME = 'autoarchive';
var TTL_LABELS = [
{
label: 'ttl1',
days: 1,
}
];
function main() {
autoArchive();
autoArchiveTTL();
}
function autoArchive() {
var autoArchiveLabel = GmailApp.getUserLabelByName('autoarchive');
// TODO: enhance with date filter already, e.g. before:
var dateString = BEFORE_DATE.toISOString().slice(0, 10); // eg. 2019-02-23
var threads = GmailApp.search("in:inbox -is:starred before:" + dateString);
// Archive all unstarred emails before the BEFORE_DATE
// Start in reverse, process them faster.
for (var i = (threads.length - 1); i >= 0; i--) {
var t = threads[i];
// sanity checks
if (t.getLastMessageDate() < BEFORE_DATE && !t.hasStarredMessages()) {
performArchive(t, autoArchiveLabel);
}
}
}
function autoArchiveTTL() {
for (i = 0; i < TTL_LABELS.length; i++) {
var ttl = TTL_LABELS[i];
var beforeDate = new Date();
beforeDate.setDate(beforeDate.getDate() - ttl.days);
var autoArchiveLabel = GmailApp.getUserLabelByName('autoarchive');
var label = GmailApp.getUserLabelByName(ttl.label);
var threads = GmailApp.search("in:inbox -is:starred label:" + ttl.label)
for (var i = 0; i < threads.length; i++) {
var t = threads[i];
if (t.getLastMessageDate() < beforeDate && !t.hasStarredMessages()) {
performArchive(t, autoArchiveLabel);
}
}
}
}
function performArchive(thread, label) {
thread.addLabel(label);
thread.moveToArchive();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment