Search code examples
google-apps-scriptgmail

Removing label from Gmail email after X days using Google Apps Script


I created a Google Apps Script Code.gs as follows to remove the Gmail label from every thread that is older than X days and labeled Y.

function archiveYThreads() {
// Every thread, older than two days, and labeled "Unread Feeds".
var threads = GmailApp.search('label:"Unread Feeds" older_than:2d');
  for (var i = 0; i < threads.length; i++) {
    threads[i].removeLabel("Unread Feeds");
}
}

According to the documentation, the function removeLabel exists. Alternatively, I found some sources that use deleteLabel. However, with both I get the error that both functions do not exist, after having set a time-based trigger:

Screenshot Function not found

Can anybody please help me detecting why the function does not work?


Solution

  • You have to supply an object of type GmailLabel as the argument to removeLabel() method. Try this snippet.

    function archiveYThreads() {
     var label = GmailApp.getUserLabelByName("Unread Feeds");
     var threads = GmailApp.search('label:"Unread Feeds" older_than:2d');
      for (var i = 0; i < threads.length; i++) {
        threads[i].removeLabel(label);
      }
    }