【问题标题】:How to overcome "Cannot find method addLabel(string)" in Gmail App Script?如何克服 Gmail 应用脚本中的“找不到方法 addLabel(string)”?
【发布时间】:2020-12-10 10:37:06
【问题描述】:

下面的应用脚本获取第一个 Gmail 收件箱线程的第一封邮件,并根据正则表达式检查“发件人:”标头。

根据结果,我们想使用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");
  }
  
  
}

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

我该如何克服这个问题?

【问题讨论】:

  • 如错误状态,没有方法addLabel(string)

标签: google-apps-script gmail


【解决方案1】:

解释:

问题在于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");
  }
  
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多