E-Mail retention policies in Gmail

·
While the bigger Google Workspace plans contain features for e-mail retention policies and e-mail auto-deletion, its smaller siblings, Gmail and the (now non-existing) “free tier of Google GWorkplace (former G Suite) don’t feature this. However, with” some scripting, you can bring a similar feature to them, too.

One of the features I miss most with my personal mail accounts is the ability to use some kind of retention policies applied to bulk messages.

While originally a compliance feature in Microsoft Exchange or the Enterprise Plans of Google Workspace, retention policies are also very useful in automatically decluttering your mailbox after a set time:

  • To delete messages with order receipts after a number of years;
  • To automatically delete newsletters after a few weeks or months; or
  • To automatically move read messages to your archives after a few days or weeks

Unfortunately, no such feature is available in the former free G Suite tier or Gmail, and no add-in has been published in the Marketplace that would allow one to achieve this in Google’s free products.

Google Scripts to the rescue#

Luckily, with the Google Script environment, one can rather easily build such a functionality and integrate it into Gmail.

After the n-th time being frustrated with the lack of this feature, and inspired by Gmail Automation: 5 Useful Google Scripts to Automate Your Gmail, I wrote some code that

  • lets you define any number of policies that either delete or archive a message threads after a number of days have passed since the last message sent/received in that thread; and
  • lets you apply these through filters or manually to message threads

Building your E-Mail retention policy automation#

With the Gist published here, you can implement this for your Gmail / Google Mail accounts as well:

  • Go to Google Scripts and create a blank project (make sure you are logged into your Google account);
Google Script Blank Project
  • paste the code (below) (and modify the policies as needed);
/****
 * This Script will apply different e-mail policies according to a defined set of labels
 * Actions:
 *  - Delete: will delete (move) the message thread to the trash (unless starred)
 *  - Archive: will move the thread to the archive
 *
 * New policies: To add a new policy, add a new entry in the "policies" map
 *
 * When executing the action, the corresponding label will be removed. This will speed up the
 * processing of messages considerably (otherwise, the messages would be reprocessed on every run).
 * Starred messages will not be deleted.
 *
 * By setting a timed trigger, you can execute the script in regular intervals (e.g. every 30 minutes)
 * Create a filter that will apply a specific label automatically to the filtered mail and
 * your mailbox will unclutter itself automatically.
 *
 * Inspired/adapted from https://www.maketecheasier.com/google-scripts-to-automate-gmail/
 */

function applyEmailPolicy() {
  var policies = {
    // Archive Policies
    monthArchive: {
      label: "Archive After 30 Days",
      days: 30,
      action: "archive",
    },
    weekArchive: { label: "Archive After 1 Week", days: 7, action: "archive" },
    biWeeklyArchive: {
      label: "Archive After 2 Weeks",
      days: 14,
      action: "archive",
    },

    // Delete Policiess
    monthDelete: { label: "Delete After 30 Days", days: 30, action: "delete" },
    yearDelete: { label: "Delete After 1 Year", days: 365, action: "delete" },
    decadeDelete: {
      label: "Delete After 10 Years",
      days: 3650,
      action: "delete",
    },
  };

  for (var policyKey in policies) {
    var policy = policies[policyKey];
    Logger.log("Applying E-Mail Policy '" + policy["label"] + "'");
    var label = GmailApp.getUserLabelByName(policy["label"]);

    if (label == null) {
      GmailApp.createLabel(policy["label"]);
    } else {
      var delayDays = policy["days"];
      var maxDate = new Date();
      maxDate.setDate(maxDate.getDate() - delayDays);

      var threads = label.getThreads();
      for (var i = 0; i < threads.length; i++) {
        if (threads[i].getLastMessageDate() < maxDate) {
          switch (policy["action"]) {
            case "delete":
              if (!threads[i].hasStarredMessages()) {
                Logger.log(
                  "Deleting Thread '" +
                    threads[i].getFirstMessageSubject() +
                    "'"
                );
                threads[i].removeLabel(label);
                threads[i].moveToTrash();
              } else {
                Logger.log(
                  "Skipping Thread '" +
                    threads[i].getFirstMessageSubject() +
                    "'"
                );
              }
              break;
            case "archive":
              Logger.log(
                "Archiving Thread '" + threads[i].getFirstMessageSubject() + "'"
              );
              threads[i].removeLabel(label);
              threads[i].moveToArchive();
              break;
          }
        }
      }
    }
  }
}
  • run the script manually and Gmail will
    • ask you for the permissions needed to work properly (it grants your script read/write access to your mailbox which is needed to move / delete the messages); and
    • will create the labels for each policy you defined (which is needed if you want to apply them to messages afterwards)
  • set a trigger (Resources -> Current Project’s Triggers -> Add one now) to run it at the preferred interval; and
  • create filters in Gmail/Google Mail that set policies when specific messages arrive

Once you’ve labeled a number of messages, you can manually run the script again and check the logs to see if the messages are found and moved to the trash or the archive.

Caveats#

  • Please note that threads with starred messages will not be deleted by this script – starring them is an easy way to ensure important messages are not deleted accidentially;
  • If you label messages / threads older than thirty days with a delete policy, they will immediately be deleted upon execution of the script – there’s no way to retrieve them afterwards, so be careful when applying a delete policy in bulk!;
  • The archive policy will move them from the inbox to the Archive;

Credits#

Inspired and adapted from Gmail Automation: 5 Useful Google Scripts to Automate Your Gmail

Comments.

No comments. Be the first to add one!
Add a comment.
We'll never share your email with anyone else. We use the Gravatar system to pull in pictures based on an anonymous hash.
Once you submit your comment, it will be moderated and then show up here shortly after.