Skip to content

Instantly share code, notes, and snippets.

@soxofaan
Last active July 28, 2022 03:25
Show Gist options
  • Save soxofaan/92fab6776c1bfcac060544ba0c9dd59c to your computer and use it in GitHub Desktop.
Save soxofaan/92fab6776c1bfcac060544ba0c9dd59c to your computer and use it in GitHub Desktop.

Google Apps Script to automatically delete mails with a certain label after a certain time

Usage

  1. Think of a deletion scheme and create GMail labels accordingly (e.g. I use labels 'todelete/after1week', 'todelete/after1month' and 'todelete/after3months' here)
  2. set up filters in GMail to flag desired mails with these labels
  3. create a Google Apps Script with this script (adapt function names, labels and day offsets appropriatedly) and set up triggers as desired

Disclaimer

Make sure you know what your are doing and use at your own risk. I am not responsible for erroneous deletion of your emails.

function gmailAutoDeleteAfter1Week() {
_gmailAutoDelete('todelete/after1week', 7);
}
function gmailAutoDeleteAfter1Month() {
_gmailAutoDelete('todelete/after1month', 30);
}
function gmailAutoDeleteAfter3Months() {
_gmailAutoDelete('todelete/after3months', 90);
}
// Delete Threads with given label, older than given number of days
//
// Based on:
// https://medium.com/@fw3d/auto-archive-emails-in-gmail-after-2-days-1ebf0e076b1c
// https://gist.github.com/anonymous/2cca33d376f7f924fdaa67891ad098cc
// https://gist.github.com/GabeBenjamin/3ef20889fa37ae97e9492e58e90db892
function _gmailAutoDelete(labelName, minimumAgeInDays) {
Logger.log('Running autodelete for label %s (minimum age in days: %s)', labelName, minimumAgeInDays);
// Threshold for latest message of the thread.
var thresholdDate = new Date();
thresholdDate.setDate(thresholdDate.getDate() - minimumAgeInDays);
Logger.log('Using threshold date %s', thresholdDate);
// Get all the threads with the label.
var label = GmailApp.getUserLabelByName(labelName);
Logger.log('Found label %s', label);
if (label) {
Logger.log('Found label: %s', label.getName());
var batchSize = 100;
var start = 0;
while (true) {
Logger.log('Batch %s %s', start, batchSize);
var threads = label.getThreads(start, batchSize);
if (threads.length < 1) {
Logger.log('No more threads');
break;
}
var toDelete = threads.filter(function(thread) {
return (thread.getLastMessageDate() < thresholdDate);
})
Logger.log('Found %s threads to delete', toDelete.length);
GmailApp.moveThreadsToTrash(toDelete)
// Prepare for next batch
start += batchSize - toDelete.length;
}
}
}
@simon57nz
Copy link

simon57nz commented Sep 8, 2018

I was taken by your ideas here which followed what I wanted to achieve but I have the following set up to add flexibility:
Instead of your hard coded 1 week, 1 month and 3months I am using the number of days as the second tier label.
e.g. I have labels like "autodelete/7/facebook" and "autodelete/15/linkedin"
so I am labelling my "short life mesages" by category as well as autodelete.

@fullbright
Copy link

Here is my little contribution.

Features :

  • can archive automatically your emails
  • can delete your emails (of course)
  • setup your labels like this :
    • to auto archive: toarchive/xxdays (where xx is the number of days you want the script to archive your emails)
    • to auto delete: todelete/xxdays (where xx is the number of days you want the script to delete your emails)

What I had in mind:
Let's say I have some newsletters to read. Some weeks are more busy than others. So I don't want these email to clutter my inbox. If I don't read them after 7 days, they will be automatically archived. Then if I have more time the following week, I can go and read it. If I have a busy month, the newsletter will be deleted permanently (suppose I have setup deletion after 30 days).

This workflow can apply to other emails aswell, like social media notifications.

function processToDelete(){
  GmailApp.getUserLabels().forEach((item, index) => {
    try{
      var labelName = item.getName();
      var prefix = "todelete";
      if(item.getName().startsWith(prefix + "/")){
        Logger.log("Processing label " + labelName);
        var nbDays = parseInt(labelName.replace(prefix + "/", "").replace("days", ""));

        Logger.log("Number of days " + nbDays);
        _gmailAutoProcess(labelName, nbDays, prefix);
      }
    } catch(error){
      Logger.log("An error occured. " + error);
    }
  });
}

function processToArchive(){
  GmailApp.getUserLabels().forEach((item, index) => {
    try{
      var labelName = item.getName();
      var prefix = "toarchive";
      if(item.getName().startsWith(prefix + "/")){
        Logger.log("Processing label " + labelName);
        var nbDays = parseInt(labelName.replace(prefix + "/", "").replace("days", ""));

        Logger.log("Number of days " + nbDays);
        _gmailAutoProcess(labelName, nbDays, prefix);
      }
    } catch(error){
      Logger.log("An error occured. " + error);
    }    
  });
}

// Delete Threads with given label, older than given number of days
//
// Based on:
// https://medium.com/@fw3d/auto-archive-emails-in-gmail-after-2-days-1ebf0e076b1c
// https://gist.github.com/anonymous/2cca33d376f7f924fdaa67891ad098cc
// https://gist.github.com/GabeBenjamin/3ef20889fa37ae97e9492e58e90db892
function _gmailAutoProcess(labelName, minimumAgeInDays, action) {
  Logger.log('Running autodelete for label %s (minimum age in days: %s)', labelName, minimumAgeInDays);
  
  // Threshold for latest message of the thread.
  var thresholdDate = new Date();
  thresholdDate.setDate(thresholdDate.getDate() - minimumAgeInDays);
  Logger.log('Using threshold date %s', thresholdDate);

  // Get all the threads with the label.
  var label = GmailApp.getUserLabelByName(labelName);
  Logger.log('Found label %s', label);
  if (label) {
    Logger.log('Found label: %s', label.getName());
    var batchSize = 100;
    var start = 0;
    while (true) {
      Logger.log('Batch %s %s', start, batchSize);
      var threads = label.getThreads(start, batchSize);
      if (threads.length < 1) {
        Logger.log('No more threads');
        break;
      }
      var toDelete = threads.filter(function(thread) {
        return (thread.getLastMessageDate() < thresholdDate);
      })
      Logger.log('Found %s threads to %s', toDelete.length, action);
      if(action == "todelete"){
        GmailApp.moveThreadsToTrash(toDelete)
      }

      if(action == "toarchive"){
        threads.forEach((thread) => {
          if(thread.getLastMessageDate() < thresholdDate){
            GmailApp.moveThreadToArchive(thread);
            Utilities.sleep(1000);
          }          
        });
      }
      
      // Prepare for next batch
      start += batchSize - toDelete.length; 
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment