Automatically Deleting Old Emails in Gmail

07/02/2019 Reading Time: 5 Minutes

Automatically Deleting Old Emails in Gmail

Our life runs on email and depending on the state of our inbox, life can be good or bad. If you achieve inbox zero with ease, then congrats, you are in the 1% of people who can sleep well at night knowing they are on top of their tasks and communication. For the rest of us, it is common to stay afloat with cluttered inboxes blending important emails and newsletters to websites we didn’t realize we opted into. I, like many, fall into this category with some of my email accounts, so a few days ago I decided to put an end to my email anxiety and write a script to delete dormant emails, which I will teach you how to do as well.

Start by going to https://script.google.com/ and clicking on “New Script”. Script.google.com Google’s domain for hosting scripts that run on its various products.

In the new script window, you will see a code editor containing boilerplate code for a JavaScript function. Change the function name to something more descriptive of the event that will happen when the script is run. In my case, I used `oldEmailDeletion()`.

function oldEmailDeletion() {
	//We will place our code in this function
}

Next, we will start to write our script by defining the age of an email at which it should be deleted. This is also a good time to define any other general filtering criteria you might want to use. In my case, I have gotten into the habit of labeling my newsletters so they don’t clutter my inbox and bleed into my important email threads. I don’t want the important emails deleted, but I am fine with deleting the labeled newsletters if they sit for a set amount of time. This requirement means that I will need to be more restrictive with my filtering and make it label based.

Since I am targeting newsletter emails with this script, I feel comfortable with deleting emails a week after they have been sent. In order to convert 7 days from now into a programmable format, I need to set two variables, one for the duration (daysAgo) and the other as a JavaScript date object (expirationDate) that creates a system readable timestamp. From here, I use a setDate function that changes the value of the expirationDate from today to today - 7 days.

function oldEmailDeletion() {
    //Age of email threads that will be deleted (i.e. older_than: # days)
    var daysAgo = 7;
    
    //Expiration date variable
    var expirationDate = new Date();
    
    //Set the older_than date. Any email older than this date will be deleted
    expirationDate.setDate(expirationDate.getDate()-daysAgo);
}

If you would like to apply this script to your entire email account, then skip the next step and move to the section about the loop. Otherwise, if you would like to include label filtering in the deletion process, then set your labels as strings inside the  labels array. After setting the labels, we need to loop through the array and have Gmail retrieve all of the email threads for each label we provided.

function oldEmailDeletion() {
    //Age of email threads that will be deleted (i.e. older_than: # days)
    var daysAgo = 7;
    
    //Expiration date variable
    var expirationDate = new Date();
    
    //Set the older_than date. Any email older than this date will be deleted
    expirationDate.setDate(expirationDate.getDate()-daysAgo);

    //Labels associated with emails to be included in deletion
    var labels = [
        'News',
        'Tech Newsletters'
    ];
  
}

If you are not filtering by labels, then GmailApp.getInboxThreads() can be used to retrieve all inbox threads. If you are, then use the .getUserLabelByName() method with the looped labels value.

function oldEmailDeletion() {
    //Age of email threads that will be deleted (i.e. older_than: # days)
    var daysAgo = 7;
    
    //Expiration date variable
    var expirationDate = new Date();
    
    //Set the older_than date. Any email older than this date will be deleted
    expirationDate.setDate(expirationDate.getDate()-daysAgo);

    //Labels associated with emails to be included in deletion
    var labels = [
        'News',
        'Tech Newsletters'
    ];

    //Loop through each email label found in the "labels" variable array
    for(var i = 0; i < labels.length; i++){

        //Retrieve label information based on value in "labels" variable array
        var label = GmailApp.getUserLabelByName(labels[i].toString());
    
        //Access all email threads associated with the retrieved label
        var emailThreads = label.getThreads(); //getThreads(###,###) if a specific range of email threads to retrieve

    }
  
}

Once we have fetched the threads from Google, we want to loop through each thread and their attributes and use the method .moveToTrash() if they match our criteria. If all you are looking to do is remove the emails older than the date we defined, then use emailThreads[j].getLastMessageDate() < daysAgo in an if statement, which translates to the last message date of an individual thread that is less than the day variable we defined with expirationDate. If you are looking to get even more specific, like I am, then chain together a few more attributes to ensure that you only remove the emails that you don’t care about.

Full Code (UPDATED: 7/9/19. Removed attribute filtering for brevity):

function oldEmailDeletion() {
    //Age of email threads that will be deleted (i.e. older_than: # days)
    var daysAgo = 7;
    
    //Expiration date variable
    var expirationDate = new Date();
    
    //Set the older_than date. Any email older than this date will be deleted
    expirationDate.setDate(expirationDate.getDate()-daysAgo);

    //Labels associated with emails to be included in deletion
    var labels = [
        'News',
        'Tech Newsletters'
    ];

    //Loop through each email label found in the "labels" variable array
    for(var i = 0; i < labels.length; i++){

        //Retrieve label information based on value in "labels" variable array
        var label = GmailApp.getUserLabelByName(labels[i].toString());
    
        //Access all email threads associated with the retrieved label
        var emailThreads = label.getThreads(); //getThreads(###,###) if a specific range of email threads to retrieve
    
        //Loop through each email thread set to "emailThreads" variable
        for(var j = 0; j < emailThreads.length; j++){
        
        //If an email thread is older than the expiration date, then delete
        if(lastEmail < expirationDate){
            emailThreads[j].moveToTrash();
        }
    }
  }
  
}

Once the code is written, run a test on your inbox by clicking the “Run” button. If the script runs with the intended output, then click on the clock or “Current project’s triggers”, which will bring you to a page where you can set up a time based trigger for the script to run.

Since I only need this to be a background job, I set my trigger time to run daily between midnight and 1am.

Click “Save” and you are done. You now have an automated way to delete old, unwanted emails without having to manually go through your inbox. If any issues arise you will be notified by email, but if you have followed my instructions and the code below, then errors should be at a minimum.

📬 Subscribe to My Newsletter

Get the latest articles and exclusive content straight to your inbox.