Skip to content

Instantly share code, notes, and snippets.

@nitobuendia
Last active April 24, 2020 09:47
Show Gist options
  • Select an option

  • Save nitobuendia/a8ddefbd0515c339519bba32950bf451 to your computer and use it in GitHub Desktop.

Select an option

Save nitobuendia/a8ddefbd0515c339519bba32950bf451 to your computer and use it in GitHub Desktop.
Label to delete gMail threads matching a search query - Apps Script
/**
* @fileoverview Utility to delete old threads from a search.
* This is an Apps Script code.
*
* Example of usage:
* Go to scripts.google.com and click 'New script'.
* Enable V8, as the code is written with ES6 features.
* Change QUERY_SEARCH to a gMail search/filter that matches
* the emails you want to delete. For example:
* 'label:coding older_than:1m'
* matches threads in coding label older than a month.
* Run 'deleteMatchingThreadsDryRun' to make sure it matches
* the desired threads by checking the logs.
* When confirmed, set a new recurrent trigger:
* Edit > Current project's triggers > Add trigger.
* Choose which function to run: 'deleteMatchingThreads'.
* Select type of time based trigger: hour/day/week/month
* depending on what frequency suits you.
* Click 'Save'.
*/
// Change for the search query that you want to delete.
const QUERY_SEARCH = 'label:coding older_than:1m';
/**
* Runs deleting functions without deleting threads.
* Logs messages on the number and subjects of the threads
* that would have been deleted if run.
*/
function deleteMatchingThreadsDryRun() {
_deleteMatchingThreads(/* dryRun = */ true);
}
/**
* Runs deleting functions without deleting threads.
* Logs messages on the number and subjects of the threads
* that would have been deleted if run.
*/
function deleteMatchingThreads() {
_deleteMatchingThreads(/* dryRun = */ false);
}
/**
* Deletes threads matching QUERY_SEARCH rules.
* @param {boolean=} dryRun Whether run should actually delete messages.
* If true, it won't delete it. By default, this is true.
*/
function _deleteMatchingThreads(dryRun = true) {
Logger.log('Received request to delete emails matching: ' + QUERY_SEARCH);
Logger.log('Dry run? ' + dryRun);
const matchingThreads = GmailApp.search(QUERY_SEARCH);
Logger.log('Found ' + matchingThreads.length + ' matching threads.');
for(const thread of matchingThreads) {
if (dryRun === false) thread.moveToTrash();
Logger.log('Deleting thread: ' + thread.getFirstMessageSubject());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment