如何克服 Gmail App 脚本中的 "Cannot find method addLabel(string)"?

How to overcome "Cannot find method addLabel(string)" in Gmail App Script?

下面的应用程序脚本获取第一个 Gmail 收件箱线程的第一条消息,并根据正则表达式检查“发件人:”header。

根据结果,我们想使用 addLabel() 设置 Gmail 标签。

它可以很好地执行提取和测试,但在尝试设置标签时失败 - 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");
  }
  
  
}

感觉 addLabelif 子句中的存在已经剥夺了 GmailApp 的应用程序,因为我有 addLabel 在一个之外运行 - 我是对的?这是我的第一个脚本。

我该如何克服这个问题?

解释:

问题是 addLabel(label) 接受 string 而是 GmailLabel.

类型的对象

如果标签已经由您创建,您需要使用 getUserLabelByName(name),您可以将标签 name 作为 string 传递,返回一个 GmailLabel 对象最后传递给 addLabel(label).

解决方案:

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");
  }
  
}