How to delete emails after a defined period

googleIt is possible to configure Gmail to delete all emails over a certain age for any given folder. For example you might want to autmatically delete all 'Family' emails that are older than 12 months. This article describes the steps involved.

Google Auto-purge Script

Using a simple Google Script you can check email messages in a particular folder (label) in Gmail, and then purge those that have exceeded the given retention period.

  1. Start by logging on to your Gmail account.
  2. Open a new tab and browse to
  3. In the left-pane, click New script.
  4. Delete the default content
  5. To purge all emails older than 365 days in the Newsletters folder, paste the contents below in to the new document.
  6. You can change the following items to suit your needs.
    1. var GMAIL_LABEL = "Newsletters";
    2. var PURGE_AFTER = "365";
  7. Click the Project title Untitled project to rename it to 'Purge Newsletters'.
  8. Click File > Save.
  9. Click Run > Run function > Initialize.
    1. This will open a separate windown and ask you to Review permissions. You'll need to Allow the script to access your Newsletter folder.
  10. Click Run > Run function > Install.

If you'd like to run this script straightaway, you can go to Run > Run function > purgeGmail. Otherwise this script will run every day just after midnight. You can go to Run > Run function > Uninstall to stop the script from running in the future.

This script will put your emails in the bin. By default Google will empty the bin 30 days later, so in this example you would be able to access emails for upto 13 months.


// The name of the Gmail Label that is to be purged?
var GMAIL_LABEL = "Newsletters";

// Purge messages automatically after how many days?
var PURGE_AFTER = "365";

function Intialize() { return; } function Install() { ScriptApp.newTrigger("purgeGmail") .timeBased() .at(new Date((new Date()).getTime() + 1000*60*2)) .create(); ScriptApp.newTrigger("purgeGmail") .timeBased().everyDays(1).create(); } function Uninstall() { var triggers = ScriptApp.getScriptTriggers(); for (var i=0; i<triggers.length; i++) { ScriptApp.deleteTrigger(triggers[i]); } } function purgeGmail() { var age = new Date(); age.setDate(age.getDate() - PURGE_AFTER); var purge = Utilities.formatDate(age, Session.getScriptTimeZone(), "yyyy-MM-dd"); var search = "label:" + GMAIL_LABEL + " before:" + purge; try { var threads =, 0, 100); if (threads.length == 100) { ScriptApp.newTrigger("purgeGmail") .timeBased() .at(new Date((new Date()).getTime() + 1000*60*10)) .create(); } for (var i=0; i<threads.length; i++) { var messages = GmailApp.getMessagesForThread(threads[i]); for (var j=0; j<messages.length; j++) { var email = messages[j]; if (email.getDate() < age) { email.moveToTrash(); } } } } catch (e) {} }

For more details, visit the script developers website.


Thanks for visiting,