Skip to content

Instantly share code, notes, and snippets.

@nitobuendia
Created June 1, 2020 14:50
Show Gist options
  • Save nitobuendia/29762a38ddc3b9220cc8f5702995a0f2 to your computer and use it in GitHub Desktop.
Save nitobuendia/29762a38ddc3b9220cc8f5702995a0f2 to your computer and use it in GitHub Desktop.
Label to delete gMail threads matching certain 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 values to the gMail search filters
* 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',
'label:home older_than:6m',
];
/**
* 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() {
_runAllDeleteQueries(/* 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() {
_runAllDeleteQueries(/* dryRun = */ false);
}
/**
* Runs all delete matching thread queries.
* @param {boolean=} dryRun Whether run should actually delete messages.
* If true, it won't delete it. By default, this is true.
*/
function _runAllDeleteQueries(dryRun = true) {
for (const searchQuery of QUERY_SEARCH) {
_deleteMatchingThreads(searchQuery, dryRun);
}
}
/**
* Deletes threads matching given mail search query.
* @param {string} searchQuery Query whose filter to match to delete threads.
* @param {boolean=} dryRun Whether run should actually delete messages.
* If true, it won't delete it. By default, this is true.
*/
function _deleteMatchingThreads(searchQuery, dryRun = true) {
Logger.log('Received request to delete emails matching: ' + searchQuery);
Logger.log('Dry run? ' + dryRun);
const matchingThreads = GmailApp.search(searchQuery);
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