Skip to content

Instantly share code, notes, and snippets.

@shoelaced
Last active December 15, 2023 01:15
Show Gist options
  • Save shoelaced/40d6e66b81ba1fce97f2c57768fb2ba1 to your computer and use it in GitHub Desktop.
Save shoelaced/40d6e66b81ba1fce97f2c57768fb2ba1 to your computer and use it in GitHub Desktop.
Google Script: Auto-delete old Gmail emails
/**
* This script deletes Gmail email threads older than a set time.
*
* To schedule this script to run once a week:
* 1. In the Google Apps Script dashboard, click on the clock icon on the left sidebar.
* 2. Click on the '+' button at the bottom right to add a new trigger.
* 3. Set the function to "DeleteOldEmail", the deployment to "Head", and the event source to "Time-driven".
* 4. Choose the "Week timer" option and select the day and time you'd like the script to run.
* 5. Save the trigger. Ensure that you've granted the necessary permissions for the script to run.
*/
function DeleteOldEmail() {
try {
// Search for email threads older than 5 days. Adjust the "5d" as needed.
var threads = GmailApp.search("older_than:5d");
// If there are more than 0 threads, move them to trash in bulk.
if (threads.length > 0) {
GmailApp.moveThreadsToTrash(threads);
}
} catch (error) {
// Log any errors for debugging.
Logger.log("An error occurred: " + error.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment