Skip to content

Instantly share code, notes, and snippets.

@pauloconnor
Created January 4, 2016 15:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pauloconnor/b166b02777eb8887c83e to your computer and use it in GitHub Desktop.
Save pauloconnor/b166b02777eb8887c83e to your computer and use it in GitHub Desktop.
Google Script for deleting automated emails
// The name of the Gmail Label that is to be autopurged?
var LABELS = ["alerts-disk-space", "alerts-sensu", "backups", "cron", "janitor-monkey", "nagios", "push", "security-alerts", "svn-git-updates"];
// Purge messages automatically after how many days?
var PURGE_AFTER = "31";
// This is the largest batch size moveThreadsToTrash supports
var BATCH_SIZE = 100
var DELAY_BETWEEN_MS = 1000
function purgeLabel(label) {
var age = new Date();
age.setDate(age.getDate() - PURGE_AFTER);
var purge = Utilities.formatDate(age, Session.getScriptTimeZone(), "yyyy-MM-dd");
// This will create a simple Gmail search
// query like label:Newsletters before:10/12/2012
var search = "label:" + label + " before:" + purge;
while (true) {
// Grab a batch of threads
var threads = GmailApp.search(search, 0, BATCH_SIZE);
// Break if there's nothing to do
if (threads.length == 0) {
break;
}
GmailApp.moveThreadsToTrash(threads);
// Sleep in-between deletes or we may get killed for calling the API too quickly
Utilities.sleep(DELAY_BETWEEN_MS)
}
}
function main() {
for (var i=0; i<LABELS.length; i++) {
Logger.log("Deleting from %s", LABELS[i]);
purgeLabel(LABELS[i])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment