【问题标题】:Add label to an Gmail thread with only 1 message (the original message)将标签添加到只有 1 封邮件(原始邮件)的 Gmail 线程
【发布时间】:2020-02-11 16:19:05
【问题描述】:

当我向客户发送报价时,我想编写一个脚本,为电子邮件添加标签,很简单。问题是,我只想将标签添加到线程一次,然后再也不添加。我有另一个脚本,它将获取带有该标签的所有电子邮件并添加日历提醒,并将删除标签,因此它不会继续添加事件。我遇到的问题是,当客户回复第一封电子邮件时,标签会被重新应用,这会导致另一个日历事件发生。有没有办法只为消息计数为 1 的线程添加标签?所以在下图的情况下,标签应该只适用于第二个线程,而不是第一个。

Two threads, one with a single email, and one with 5

function QuoteReminder() {
  var reminderLabel = "STS Quotes", //Substitute your label here
      calendarName = "Quote Follow-ups", ////Substitute your Calendar name here
      label = GmailApp.getUserLabelByName(reminderLabel),
      threads = label.getThreads();

     if (threads.length > 0) {
       for (i in threads) {
         if (i.getMessageCount() == 1) {
          //get calendar by name
          var cals = CalendarApp.getCalendarsByName(calendarName);

          //This is run the next day around 9am, calendar invite will be created for 13 days form then to account for the next day
          var now = new Date().getTime();
          var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
          for (i in threads) {
            cals[0].createEvent(reminderLabel + '- '+ i.getFirstMessageSubject(),
             new Date(now+(MILLIS_PER_DAY*13)),
             new Date(now+(MILLIS_PER_DAY*13)+900000), {description: i.getPermalink()});
      }
      //Remove the label from the mails to avoid duplicate event creation on next run 
      label.removeFromThreads(threads);
         }
       }
     }
}

【问题讨论】:

  • 请包含您的代码
  • 对不起!刚加了。上面的代码假定标签已经存在,并将日历提醒添加到带有标签的任何线程。最初我正在寻找带有标签的线程 = 1 条消息并且遇到了问题。所以我想如果我“提升一个级别”到添加标签的位置可能会更容易,但有同样的问题,我需要查找只有 1 条消息的线程。

标签: google-apps-script gmail-api


【解决方案1】:

是的,有。

我无法为您提供复制粘贴解决方案,因为我没有看过您的代码,甚至不知道您使用的是哪种编程语言,但是

Users.threads: get 方法可以返回所有的 线程的消息。

因此,您可以合并一个简单的 if 语句来验证消息数组的长度是否大于 1,然后相应地运行其余代码。

更新:

  • 要在 Apps Script 中检索线程中的消息数,您可以使用方法getMessageCount()
  • 此消息需要应用于单个线程
  • label.getThreads() 方法返回一个线程数组
  • 要访问线程数组的单个元素,您需要使用它们在数组中的位置来寻址它们,例如threads[0]threads[1] 或 - 在循环中 threads[i]

在你的情况下:

你需要将if (i.getMessageCount() == 1) {...修改为if (threads[i].getMessageCount() == 1) {...

否则,if 语句只会验证他的计数器变量 i 是否等于 1 - 如果 threads.length > 0 ,则在其中一次迭代中总是会出现这种情况

【讨论】:

  • 谢谢!我只是把代码放在那里。我很抱歉它最初不存在。编写此代码是为了假设标签在那里并且我遇到了问题。这就是为什么我想在添加标签的地方“升级”。不过,同样的问题存在于我只需要查找带有 1 条消息的线程。
  • 我不太确定您的问题是什么,因为您已经使用了getMessageCount() 方法。所以在声明if (i.getMessageCount() == 1) {... 中你只需要添加label.addToThread(i);
  • 邮件计数无效。无论是 1 条消息还是 5 条消息,它仍然会使用该搜索查询提取所有线程。
  • 我明白了。问题在于您迭代线程的方式 - 我更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 2021-03-21
  • 2016-02-14
  • 1970-01-01
  • 2018-03-22
  • 2020-07-28
  • 1970-01-01
相关资源
最近更新 更多