Automatically delete old Gmail messages and alerts

If you are like us at SMBTexas, your email gets filled with all kinds of alerts and reports that you would like to ‘age out’ gracefully, here is a method to automatically delete old Gmail messages so you can set it and forget it using You can specify any filter you would like, including, having (or not having) attachments, unread status, older than, etc. This script includes threading to handle when you have TONS of messages that have accumulated and you are just getting around to deleting them.

DISCLAIMER: No warranties offered or implied. Not responsible for data loss. This process WILL DELETE matching email records!

Get info for filtering

  • Open Gmail and create labels and rules so these emails can be categorized for easy management. Using labels is optional but it makes things easier later on.
  • Select the label you would like to manage to bring them into view, and note the search string in the search bar; We will need this string later.

Create project

  • Open and click ‘New project’. Rename your project in the top bar to something descriptive, e.g. ‘Mass Delete Gmail’.
  • In the Editor section (Labeled ‘<>’ in the left navigation) under Files ->, copy in this script:
function batchDelete() {
  var batchSize = 100 // Process up to 100 threads at once
  var threads ='label:ban-alerts older_than:200d');
  for (j = 0; j < threads.length; j+=batchSize) {
    GmailApp.moveThreadsToTrash(threads.slice(j, j+batchSize));

(This script will delete up to 100 threads of emails that match the .search method. In this example, any emails labeled ‘ban-alerts’ that are also older than 200 days are on the chopping block. Update the .search method with your filter information from above.)

Test the script

  • Use the ‘Run’ button to give this script a try. Please note this will delete matching email from Gmail! You will have to authorize your named project to have access to your Gmail account. At the bottom half of the page, you will see an update after a few minutes showing the status.

Configure the schedule

  • Once your ‘Run’ action is complete, under ‘Triggers’ in the left navigation, add a trigger with the following settings. You may have to re-authorize the app to access Gmail.

(Note: If you set a faster interval you’ll reach the limit for calls to GmailApp. Setting to every hour should keep this from happening.)

That is it! You now have a scheduled method to keep those emails in check!

Contact Us