在Gmail中为电子邮件添加标签失败

Add label to emails in Gmail fails

本文关键字:添加 加标签 失败 电子邮件 Gmail      更新时间:2023-09-26

我们正在尝试将Gmail中的标签添加到线程中。两个var都输出相同的"2014/10月/Sent"但只有SentLabel2有效,如果我们设置SentLabel threads[i].addLabel(SentLabel);,它将失败。

我们需要它是SentLabel,因为我们已经做了这样一个自动月份的事情(它得到了当前月份,这样我们就不需要每个月手动进入脚本并更改变量):

  var SentLabel = "2014/" + monthInWords[d.getMonth()] + "/Sent";

以下是它现在的样子:

 function wtf2() {
        var SentLabel = "2014/October/Sent";
        var SentLabel2 = GmailApp.getUserLabelByName("2014/October/Sent");

      var threads = GmailApp.getInboxThreads(0, 5);
      for (var i = 0; i < threads.length; i++) {
        var labels = threads[i].getLabels()[0];          
     threads[i].addLabel(SentLabel);
    }
    }

下面的语句之所以失败,是因为SentLabel是一个字符串变量,而不是gmailLabel变量。

threads[i].addLabel(SentLabel);

为了解决这个问题,你需要有条件地创建一个gmailLabel变量(我将称之为var标签),这取决于它是否已经存在。以下是您的操作方法:

 var label = GmailApp.getUserLabelByName(SentLabel);  //declares a variable called label and initializes it to be the value thats returned when searching GmailApp for any label that is named the same as the string you provided in your SentLabel variable
    if (label) { //if gmail finds a matching label
      Logger.log('Label exists.');
    } else {
      Logger.log('Label does not exist. Creating it.');
      label = GmailApp.createLabel(SentLabel);
    }

一旦运行,你就会有一个标签变量,如果你把它改成这个,你的语句就会起作用:

threads[i].addLabel(label);

您可以在此处阅读有关GmailLabel类的信息,https://developers.google.com/apps-script/reference/gmail/gmail-label#