Search code examples
javascriptgoogle-apps-scriptgmail

Why do I get an Invalid Argument when using the removeLabel function in Google Script


I'd like to remove my user created label called "Add-to-Spendee-2", from a collection of emails. I've pretty much followed Google's removeLabel() Documentation to the dot on this, but I keep getting an "Invalid argument: label" error.

Here's the code:

function removeLabel()

{
  var myLabel = GmailApp.getUserLabelByName('test-add-to-spendee-2');
  var threads = GmailApp.search("label:test-add-to-spendee-2 AND from:swiggy AND subject:(Your receipt for Swiggy order)");

  for (var x in threads) 
  {
  var thread = threads[x]
  thread.removeLabel(myLabel)
  }
  
}

Note: If I substitute the removeLabel(myLabel) with any other function like markUnread(), the code works perfectly.


Solution

  • I think your code will work but I think all you need to do is:

    var lbl=GmailApp.getUserLabelByName('Q0/Subject/Name');
    var threads=GmailApp.search('label:Q0/Subject/Name');//exactly as you created it
    lbl.removeFromThreads(threads);
    

    Try using the debugger and make sure that threads is getting an array of GmailThread objects.

    enter image description here

    This is what the label look like in the Gmail search window:

    enter image description here

    They changed the slashes to dashes and used lower case and that's not really what the label looks like.

    As I said above in my comment:

    I just did that recently and I found that the description of the label in the gmail search window did not agree with how I actually created the label. It displayed a label like this q0-subject-name and I had it created as Q0/Subject/Name when I used q0-subject-name I couldn't find the label and when I used Q0/Subject/Name I found it.