Last Updated: February 25, 2016
·
1.215K
· diurnalist

Set up a script to clean up old GMail threads

I follow a lot of projects on Github. As such, I get a lot of email that I only glance at occasionally, just to get a high-level view at the repo activity. I don't need these emails more than, say, past a week. It would be cool if I could just set up GMail to automatically delete emails older than a week, if they match certain criteria.

In my case, I set up a label called "Github", and any incoming Github notifications are automatically tagged with the label. Then, I set up a simple Google Apps Script to run once a day to flush any emails with that label that are over a week old.

/**
 * Moves any threads with a given label older than 1 week to the trash
 */
function flushLabel(labelName) {
  var threads = GmailApp.search("older_than:7d label:" + labelName);

  for (var i = 0, thread; thread = threads[i++];) {
    thread.moveToTrash();
    Logger.log("Trashing " + thread.getFirstMessageSubject());
  }
};

/**
 * Arguments cannot currently be passed to functions running on a schedule.
 * Each label that should be flushed automatically has its own function.
 */
function flushGithub() {
  flushLabel("Github");
};

To schedule a script to run once a day, go to the triggers section (looks like a stopwatch with a pointer in the UI) and set up a Time-driven trigger to run whatever function you want.