Skip to content

Instantly share code, notes, and snippets.

@kamermans
Last active December 12, 2019 07:44
Show Gist options
  • Save kamermans/c7e588619bc648ee73d4871721657545 to your computer and use it in GitHub Desktop.
Save kamermans/c7e588619bc648ee73d4871721657545 to your computer and use it in GitHub Desktop.
Delete all Gmail / Google Apps Email threads in a given label, even hundreds of thousands of emails.
/*
* Delete all Gmail / Google Apps Email threads in a given label.
* This is really only necessary when you have tons (read: hundreds
* of thousands) of messages to delete and the web interface crashes.
*
* Warning: if you don't understand this code, you might just delete
* all of your email!
*
* Author: Steve Kamerman, 2017
*
* To use, go to https://script.google.com and paste this in the window
* Then update the `label` var to contain the label you want to delete
* your mail from. Then run the function `deleteMessages`. When it's
* finished, press CTRL-Enter to see the log of what happened. If all
* looks well, set `dry_run` to `true`, then setup a trigger for this
* run every 5 minutes. Eventually all the messages will be gone and
* you can remove the trigger.
*/
function deleteMessages() {
var label = "Inbox/Some Label Name";
var dry_run = true;
deleteAllMessagesWithLabel(label, dry_run);
}
function deleteAllMessagesWithLabel(label, dry_run) {
var start = new Date();
var end = new Date();
var duration = 0;
// Max number of threads to fetch and delete at one time
var max_threads = 500;
// Get all the threads for this label
var label_obj = GmailApp.getUserLabelByName(label);
if (!label_obj) {
Logger.log("Error: Label does not exist: "+label);
printLabels();
return;
}
var threads = label_obj.getThreads(0, max_threads);
if (!threads) {
Logger.log("No threads found");
}
if (dry_run) {
// we archive all the threads if they're unread AND older than the limit we set in delayDays
for (var i = 0; i < threads.length; i++) {
Logger.log("First subject in thread: "+threads[i].getFirstMessageSubject());
return;
}
} else {
var deleted_threads = 0;
// If this time is exceeded, the task is aborted to prevent jobs from piling up
var max_time = 4 * 60;
// Batch size for delete action - cannot exceed 100
var batch_size = 100;
while (threads.length && duration < max_time) {
var this_batch_size = Math.min(threads.length, batch_size);
var this_batch = threads.splice(0, this_batch_size);
GmailApp.moveThreadsToTrash(this_batch);
deleted_threads += this_batch_size;
end = new Date();
duration = (end.getTime() - start.getTime()) / 1000;
}
Logger.log("Deleted "+deleted_threads+" threads in "+duration+" seconds");
}
}
function printLabels() {
var labels = GmailApp.getUserLabels().map(function(label) {
return label.getName();
});
Logger.log("Labels: \n " + labels.join("\n "));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment