Cleaning up your Gmail account with a handy script

When i logged in to Gmail this morning i clicked “All Mail” and saw that i had over 44000 emails in my account. Sure, the search feature is great but i still find it annoying that year old notifications from linkedin litter my mailbox.

So i started searching with queries like “” and mass-deleting these emails. Half an hour into this process i realized that I’m hardly making a dent and that there must be a better way. Sure enough, some Googling later i came up with this handy-dandy script.

function cleanUp() {
  // Change the queries to your linkng. Anything that matches these - the exceptions below will be trashed.
  var queries = ['"login alert"',
  '"manage your subscription"',
  queries.forEach(function(query) {

function search(query) {
  // Here are some exceptions that should never be trashed.
  var fullQuery = query + " -from:wife -\"Wifes full name\" -is:starred -label:licenses -in:trash";
  Logger.log("Searching for " + fullQuery);
  return, 0, 50);

function deleteOldThreads(threads) {
  // Set how old an email must be before it is trashed.
  var delayDays = 90
  var maxDate = new Date();
  for (var i = 0; i < threads.length; i++) {
    if (threads[i].getLastMessageDate()<maxDate) {
  Logger.log("Trashed " + threads.length + " threads.");


Before you begin, open your Gmail account and empty your trash. This will serve as a safety net in case the script trashes anything important.

Now go to and create a new script. Paste the above script and edit it to your liking.

What you may want to change:

  1. The queries. They will catch a lot of noise but not everything. Add or remove whatever you want. The queries are in the same format that you can type into the search box in Gmail.
  2. The string appended to the query inside the search function. This is a safety net that in my case never trashes email from my wife, emails that are starred or have the label “licenses”. -in:trash just makes sure that the script doesn’t bother with already trashed messages.
  3. delayDays. This is how old a message must be to be trashed. It will then stay in the trash for another 30 days until it is gone “forever”.

Give your script a test run and check your trash. Rinse and repeat.

The script will only trash a maximum of 50 emails from each search query because the script has a run limit of 6 minutes. When you are happy with the results and no important emails are being trashed, just schedule it to run once an hour using the script trigger feature and just leave it. Enjoy your clean mailbox!

Leave a Reply

Your email address will not be published. Required fields are marked *