How to Auto-Clean your Gmail’s Spam & Trash Folders

Cleaning our email inboxes is a time-consuming & annoying habit. With all those unwanted emails piling up in our Spam and Trash folders, it becomes impossible to ignore all the garbage, so you just feel like sitting down & getting rid of everything once & for all.

But just a few days later, you find yourself back in the same place because there’s no stopping spam nowadays. Gmail claims to auto-delete your old emails in the Spam and Trash every 30 days but by that time, the folders have accumulated thousands of messages, so waiting for so long is not an option.

I used to find myself doing this manual labor every morning, and over time, I realized those 2 minutes would add up, hurting my productivity.

So I set out to automate the process. Mind you, I’m not a programmer, nor a techie, and definitely not a computer science guy.

I just love to figure out solutions to problems, so I challenged myself to search for workarounds online and felt I should document my learnings for other readers. On that note, the codes you’re about to see were written by some other people (who I’ve duly credited in the end).


The Setup

Upon some digging, I located 2 “scripts” for this purpose online. Scripts are instructions that allow you to make any computer-dependent task run on its own.

Gmail doesn’t allow you to directly “delete” spam as such, because it first transfers it to the trash bin, so we’ll need two connected codes to get the job done.

  • The first script bot trashes all the emails in my SPAM folder every 4 hours. I’ve set this grace period to allow myself some time to view OTP emails or other important legitimate emails that land in the spam folder by mistake.
  • The second script bot then deletes all the emails in my TRASH (junk) folder every 12 hours. The 12h buffer is to give me some time to locate & retrieve any missed emails from colleagues or clients that were mistakenly marked as spam and then transferred to trash by my first script bot.
  • Taken together, these 2 scripts keep my inbox clean every day.

Script 1: Send Spam to Trash

As I mentioned, the first script automatically trashes all the emails that have been sitting in my spam folder for more than one hour. Why not trash them instantly? Because then I’d not get those OTP or confirmation emails when I sign up for new accounts online.

However, I would have to manually run this bot to see the effect. To resolve that, I set a time-based “trigger,” prompting it to run by itself every 4 hours.

You can directly use my script by clicking here. But in case you want to experiment, here are the instructions to set it up yourself.

  • First, log into your Google account, and go to https://script.google.com/
  • On the sidebar, click “New Project.”
  • Then delete the placeholder generic code written there (use Ctrl+A to select all, then Del to delete)
  • Paste this code
function Sent_to_Trash() {
  var threads = GmailApp.search('older_than:1h in:spam');
  for (var i = 0; i < threads.length; i++) { 
    threads[i].moveToTrash(); 
  }
}
  • Click the “Save” icon & give your script a name (e.g. Delete Spam email Script)
  • Click the “Run” icon.
  • It should open a prompt saying you need to provide authorization for the script to access your inbox
  • Click “Ok” & proceed
  • The system will warn you that this script may not be safe and you should go back. Just ignore it and click on “Advanced,” which will give you the option of continuing.
  • Enter your account details and give it all the permissions (Allow)

Then, you can run the script and check if it worked by looking at the execution log below, which will say “Execution Completed.” Go to you Spam folder in the inbox to check if it worked.

Now the next step is to set a time-based trigger so that this script runs on its own every 4 hours (or at any interval of your choice).

  • To do that, just go to the “Clock” icon on the left bar of your code screen, and “Add Trigger.”
  • Under the Event Source, select “Time Driven,” and under the Time-based Trigger option, select the interval you’d like (e.g. every x minutes, hours, or days)
  • Select the frequency (e.g. every 4 hours), and hit “Save.”

I’ve tested it and it works smoothly.


Script 2: Empty my Trash

Sending Spam to trash is not enough as it will just transfer the garbage from one location to another. So we need to set up another automation to empty the trash folder and permanently delete all the emails sitting there.

You can find and replicate my script for this here, or set it up yourself with the instructions below.

  • Log into your Google account, and go to https://script.google.com/
  • Click “New Project”
  • Then delete the placeholder generic code written there (use Ctrl+A to select all, then Del to delete)
  • Paste this code but replace my email ID with yours
function removeMyTest2() {

var mymail = "manikmarketing98@gmail.com";

var mylabel = "trash";

var permanentlyRemoveMyLabel = true;

var pageToken;

do {

    var threadList = Gmail.Users.Threads.list('me', {

    q: 'in:' + mylabel,

    pageToken: pageToken

    });

    if (threadList.threads && threadList.threads.length > 0) {

        threadList.threads.forEach(function(thread) {

        Logger.log('id: %s snippet: %s', thread.id, thread.snippet);

        if (permanentlyRemoveMyLabel) {

            Gmail.Users.Threads.remove(mymail, thread.id);

            Logger.log('id: %s snippet: %s REMOVED', thread.id, thread.snippet);

        }

    });

   }

   pageToken = threadList.nextPageToken;

   } while (pageToken);

}
  • Click the “Save” icon & give your script a name (e.g. Empty Trash folder Script)
  • Now go to Services on the left bar, click “+” and scroll down the list to add the “Gmail API”
  • Then click the “Run” icon on your script
  • It should open a prompt saying you need to provide authorization for the script to access your inbox
  • Click “Ok” & proceed
  • The system will warn you that this script may not be safe and you should go back. Just ignore it and click on “Advanced,” which will give you the option of continuing.
  • Enter your account details and give it all the permissions (Allow)

Then, you can run the script and check if it worked by looking at the execution log below, which will say “Execution Completed.” Go to your Trash folder in your inbox, and if it’s empty, you’ll know it worked.

Now the next step is to set a time-based trigger so that this script runs on its own every 12 hours (or at any interval of your choice). I’ve set 12 hours as my limit because there may be times that important emails somehow land in my Spam by mistake, and get automatically transferred here after 4 hours because of the first script.

If I had set the time for this script to run every 4 hours, too, it would permanently delete that email (now sitting in the Trash), and I wouldn’t have any access to it. So those extra 8 hours are just a fail-safe in case I need to visit the Trash folder to check for an email.

  • To set up your Time trigger, just go to the “Clock” icon on the left bar, and “Add Trigger.”
  • Under the Event Source, select “Time Driven,” and under the Time-based Trigger option, select the interval you’d like (e.g. every x minutes, hours, or days)
  • Select the frequency (e.g. every 12 hours), and hit “Save.”

I’ve tested this script, too, and so far, it’s running exactly as it should in tandem with the first one.

So this is how I resolved a technical problem that was bugging me, despite having no understanding of coding or computer science.

Sometimes it’s just about taking the efforts to Google your question and do a deep intensive search. You’ll almost always find a workaround. Bless the internet!


Credits

I found the first script on Stack overflow. It was a part of the comment by Jonathan, in which he corrects a previous answer that had an error.

I found the second script on Stack Exchange. It was submitted by FadedTrason (edited by Ruben) in response to the same question I had.

What do you think of my process? Are you a programmer who has more elegant solutions for this? Please enlighten me know in the comments below.

Published by Manik Rege

Hey there! Full disclosure, I'm a bit of a mess. But my interests range from Career Growth Strategy to Marketing & Branding, and Animal Rights to filter coffee. Same vibe? Tweet to me @manik_rege.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: