Mass delete of Gmail emails

Using Google Apps Script to clear your old emails

August 27, 2020

Gmail used to be the reference for "infinite email storage". Not anymore. The space growth stopped, and then Google started selling storage space.

It wouldn't be an issue if it were easy to mass delete emails; unfortunately batch delete operations can be quite long, and even lock you out of you inbox; using the UI, it might even regularly fail. I subscribe to many mailing lists, so I had hundreds of thousands of old emails to delete, I went looking for a new solution.

For this I used Google Apps Script to run js code on Google's servers to do this delete operation. The goal is to delete the result of search, or a label.

Here is the code to copy/paste in an Apps Script project:

function deleteOldEmail() {
  var batchSize = 100;
  var threads = [0, ];
  while (threads.length > 0) {
    threads = GmailApp.search('label:Lists-linux-kernel OR label:Lists-stable -{to:me OR from:me} before:2020/8/1');
    for (j = 0; j < threads.length; j+=batchSize) {
      GmailApp.moveThreadsToTrash(threads.slice(j, j+batchSize));
    }
  }
}

(based on this gist or this answer). You'll need to grant it access to gmail.

Here the emails from the search are moved to trash in batch of 100. Moved to thrash because direct deletion of email threads cannot be batched in the same way. Emptying trash is slightly faster than deleting those emails, and once enough space is freed, you can wait for the 30 days deadline to empty the trash automatically.

You can then schedule this deleteOldEmail function regularly by adding a time-based trigger: it will timeout a few times at first if you have a lot of emails, so you want it to be run again to complete the operation.

There are few limits to know about:

  • here the batch size corresponds to the maximum size of a moveThreadsToTrash operation
  • when scheduling it, you don't want to go over the daily limits. I've found that once every 4 hours is enough to be just below the limit (3 hours per day, with 30 minutes per run until timeout).

Depending on how many emails you have, it will complete after a few days. That's it!

Continue reading→