Archive Old Email Messages in Gmail Automatically

The Google Script will archive all email threads in a specific Gmail label that have been inactive for more than a week. It takes the date of the last message in a thread and if it is older than a week, the thread is archived. The current labels is removed as well.

function ArchiveOldEmails(gmailLabelName) {
  var gmailLabel = GmailApp.getUserLabelByName(gmailLabelName);

  var ONE_WEEK = 60 * 60 * 24 * 7 * 1000;

  var threads = label.getThreads();
  var now = new Date();

  for (var j = 0; j < threads.length; j++) {
    if (now - threads[j].getLastMessageDate() > ONE_WEEK) {
      threads[j].moveToArchive().removeLabel(gmailLabel);
    }
  }
}

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & recognition

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻