Skip to content

Instantly share code, notes, and snippets.

@alecs
Last active September 6, 2024 13:42
Show Gist options
  • Save alecs/144632920109560eb7218737f67745c0 to your computer and use it in GitHub Desktop.
Save alecs/144632920109560eb7218737f67745c0 to your computer and use it in GitHub Desktop.
gmail - delete emails in threads
function dothedew() {
emptyGmail();
deleteTrashEmailsPermanently();
}
function emptyGmail() {
var mymail = "[email protected]";
var labels = ['INBOX', 'Archive/CSV', 'Archive/Purchase', 'Builder', 'Junk', 'Logwatches', 'MySQL', 'Notes' ]; // Add your labels here
labels.forEach(function(label) {
var pageToken;
do {
processEmail('in:' + label , 'moveThreadsToTrash');
} while (pageToken);
})
}
function deleteEmailsPermanently(emailThread) {
Gmail.Users.Threads.remove('me', emailThread.getId());
}
function deleteTrashEmailsPermanently() {
do {
var trashMailThreads = GmailApp.getTrashThreads(0,400);
console.log('Got a list with size: ', trashMailThreads.length);
console.log('Now Deleting Trash Emails permanently');
trashMailThreads.forEach((trashMailThread) => {
console.log('Deleting email thread with Subject :', trashMailThread.getMessages()[0].getSubject());
deleteEmailsPermanently(trashMailThread);
});
} while (trashMailThreads.length>0)
}
function processEmail(search, batchAction) {
var batchSize = 100; // Process up to 100 threads at once
var searchSize = 400; // Limit search result to a max of 500 threads. (google doesn't allow more)
do {
var threads = GmailApp.search(search, 0, searchSize);
console.log('processing ' + threads.length + ' threads');
for (j = 0; j < threads.length; j += batchSize) {
console.log('removing batch: ' + j + '-' + Number(j + batchSize));
GmailApp[batchAction](threads.slice(j, j + batchSize));
}
console.log('done with search size: ' + threads.length);
} while (threads.length>0) // keep script running until there are no threads left
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment