1
votes

The below App Script fetches the first message of the first Gmail Inbox thread and checks the "From:" header against a regular expression.

Based on the outcome, we want to use addLabel() to set a Gmail label.

It performs the fetch and test fine, but fails when attempting to set the label - Cannot find method addLabel(string). (line 15, file "Code")

function myFunction() {
 
  // Get first thread in Inbox.
  var thread = GmailApp.getInboxThreads(0,1)[0];
  // Get the first message in the thread.
  var message = thread.getMessages()[0];
  // Get a message header
  var headerstring = message.getHeader("From");
  
  // Check header for "rob" test string, apply label
  if ( headerstring.match(/rob/g) ) {
    thread.addLabel("MyLabel");
    Logger.log("Matched rob");
  } else {
    thread.addLabel("AnotherLabel"); // failing, not class scope?
    Logger.log("No match");
  }
  
  
}

It feels like the existence of addLabel within the if clause has robbed it of the application of GmailApp, since I have had addLabel functioning outside of one - am I right? This is my first script.

How can I overcome this?

1
As the error states, There is no method addLabel(string) - TheMaster

1 Answers

1
votes

Explanation:

The issue is that addLabel(label) does not accept a string but an object of type GmailLabel.

If the labels are already created by you, you need to use getUserLabelByName(name) where you can pass the label name as string, get a GmailLabel object back and finally pass it to addLabel(label).

Solution:

function myFunction() {
 
  // Get first thread in Inbox.
  var thread = GmailApp.getInboxThreads(0,1)[0];
  // Get the first message in the thread.
  var message = thread.getMessages()[0];
  // Get a message header
  var headerstring = message.getHeader("From");
  
  // Check header for "rob" test string, apply label
  if ( headerstring.match(/rob/g) ) {   
    var label = GmailApp.getUserLabelByName("MyLabel");
    thread.addLabel(label);
    Logger.log("Matched rob");
  } else {
    var label = GmailApp.getUserLabelByName("AnotherLabel");
    thread.addLabel(label);    
    Logger.log("No match");
  }
  
}