Last active
October 8, 2016 01:50
-
-
Save kmosher/4bae356a7812fadbc370 to your computer and use it in GitHub Desktop.
Gmail Bulk Deletion and Pruning
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A script for bulk deleting emails in the background and preventing future buildup | |
// Allows you to continue to use your gmail inbox while it runs. | |
// | |
// Instructions for use | |
// -------------------- | |
// 1. Put this in a new project on script.google.com | |
// 2. Edit the LABELS or even the search construction to fit your needs | |
// 3. Set a trigger to run main() every 5 minutes. Why 5 minutes? That's the longest a script is allowed to run, | |
// so your script will also get killed every 5 minutes if it's busy trying to delete a lot of mail | |
// The name of the Gmail Label that is to be autopurged? | |
var LABELS = ["batch-cron", "cron", "nagios"]; | |
// Purge messages automatically after how many days? | |
var PURGE_AFTER = "31"; | |
// This is the largest batch size moveThreadsToTrash supports | |
var BATCH_SIZE = 100 | |
// Gmail recommends minimum 1000, but bumped after it started yelling | |
// at me recently | |
var DELAY_BETWEEN_MS = 15000 | |
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]) | |
} | |
} | |
function main() { | |
for (var i=0; i<LABELS.length; i++) { | |
purgeLabel(LABELS[i]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment