Search code examples
google-apps-scriptgmailgmail-api

How to remove user Labels from Gmail using GScript


In relation to another question that removes Category Labels, I'd like to use the same code and simply add other user labels to the routines created.

The routines are as follows:

function removeLabelsFromMessages(query, labelsToRemove) {
  var foundThreads = Gmail.Users.Threads.list('me', {'q': query}).threads
  if (foundThreads) {
    foundThreads.forEach(function (thread) {
      Gmail.Users.Threads.modify({removeLabelIds: labelsToRemove}, 'me', thread.id);
    });
  }
}

function ProcessInbox() {
  removeLabelsFromMessages(
    'label:updates OR label:social OR label:forums OR label:promotions',
    ['CATEGORY_UPDATES', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS', 'CATEGORY_PROMOTIONS']
  )

  <...other_stuff_to_process...>
}

I'm wondering if you can add another user label to the "labelsToRemove" - I've tried simply adding another label to the array, but keep getting an error stating the label cannot be found. I'm' sure it's just a syntax error (I don't code very much), so any suggestions on how to add that?

The code I'm trying to run is:

function CleanReceipts () {
  removeLabel (
    'label: Receipts', 
    ['CATEGORY_UPDATES', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS', 'CATEGORY_PROMOTIONS', '@SaneLater']
  )
}

where "@SaneLater" is the name of a user label I'd like to remove as well. Thanks in advance.


Solution

  • The reason you are getting the Label not found error is because the threads.modify method is expecting a label id and not a label name.

    In order to retrieve the id of this specific label, I suggest you take a look at labels.list and make the request to get the appropriate value:

    let labels = Gmail.Users.Labels.list('me');
    console.log(labels);
    

    Reference