Skip to content

Instantly share code, notes, and snippets.

@brutasse
Created July 5, 2014 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brutasse/9be59597f10d457c2ffe to your computer and use it in GitHub Desktop.
Save brutasse/9be59597f10d457c2ffe to your computer and use it in GitHub Desktop.
// The name of the Gmail Labels that are to be purged
var GMAIL_LABELS = [
"list",
"of",
"labels",
"to",
"purge",
];
// Purge messages automatically after that many days
var PURGE_AFTER = "365";
/*
Originally from http://labnol.org/?p=27605, adapted
to support a list of labels instead
Add this file to your google drive, set your labels
and the TTL and add a trigger to run it every 2 hours.
If you have very old threads it's best to purge them
manually first, otherwise you'll run into rate-limiting
issues quickly:
- search for "label:<label> before:2014-07-05"
- select all
- delete
*/
function purgeGmail() {
var age = new Date();
age.setDate(age.getDate() - PURGE_AFTER);
var purge = Utilities.formatDate(age, Session.getTimeZone(), "yyyy-MM-dd");
for (var k=0; k<GMAIL_LABELS.length; k++) {
var search = "label:" + GMAIL_LABELS[k] + " before:" + purge;
var threads = GmailApp.search(search);
if (threads.length == 0) {
Logger.log("Nothing to delete in " + GMAIL_LABELS[k]);
}
for (var i=0; i<threads.length; i++) {
var messages = GmailApp.getMessagesForThread(threads[i]);
for (var j=0; j<messages.length; j++) {
var email = messages[j];
if (email.getDate() < age) {
Logger.log("Deleting " + email.getSubject() + " from " + email.getFrom());
email.moveToTrash();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment