Skip to content

Instantly share code, notes, and snippets.

@pinkeen
Created May 30, 2020 17:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinkeen/9f3014939f8681b4f71666efc2763a13 to your computer and use it in GitHub Desktop.
Save pinkeen/9f3014939f8681b4f71666efc2763a13 to your computer and use it in GitHub Desktop.
Clean GMail Google Apps Script
/*************************************************************************************************
* Simple Google Apps script for removing GMail messages
*
* Rationale: If you've got hundreds of thousands of e-mails (automated error reports in my case)
* filling up your account's quota and there's too many of them creating huge threads so
* GMail GUI, IMAP or anything else cannot handle this removal.
*
* Usage: Set up your query and run this script using a trigger every 5/10 minutes - it took days
* for my Inbox to be finally free from the crap.
*************************************************************************************************/
function myFunction() {
var total = 0,
batch = 1;
console.time('total');
console.time('batch');
while (batch) {
batch = searchAndRemove('to:"account+spam_comment@example.com"');
console.timeEnd('batch');
console.log('Removed ' + batch + ' threads in batch ' + total + ' total ');
total += batch;
console.time('batch');
}
console.timeEnd('batch');
console.log('Removed ' + total + ' threads in total');
console.timeEnd('total');
}
function searchAndRemove(searchQuery) {
var threadsResponse = Gmail.Users.Threads.list('me', {
q: searchQuery,
maxResults: 100,
includeSpamTrash: true
});
threadsResponse.threads.forEach(function(threadData) {
try {
Gmail.Users.Threads.remove('me', threadData.id);
} catch (e) {
console.error(e);
}
});
return threadsResponse.threads.length;
}
@ethaniel
Copy link

Thank you! Thank you! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment