使用 Google Apps 脚本自动移动/应用标签到 Gmail

Mes*_*ika 4 gmail google-apps google-apps-script gmail-api google-workspace

我正在尝试为我的 G Suite 邮箱制作一个自动归档脚本。

该脚本包含一个搜索查询,然后应该获取所有找到的结果,从收件箱中删除并向其添加自定义标签(存档)。

我正在努力解决这个问题addLabel。它抛出一个错误,InternalError: Cannot find method addLabel(string).但是当我检查文档时,它似乎是正确对象上的正确方法。

任何帮助,将不胜感激。

自动 Gmail 归档

var ARCHIVE_LABEL = "archived";    
var AUTO_ARCHIVE_AFTER = "30";

function Intialize() {
  return;
}

function Install() {

  ScriptApp.newTrigger("autoArchive")
           .timeBased()
           .at(new Date((new Date()).getTime() + 1000*60*2))
           .create();

  ScriptApp.newTrigger("autoArchive")
           .timeBased().everyDays(1).create();

}

function Uninstall() {

  var triggers = ScriptApp.getScriptTriggers();
  for (var i=0; i<triggers.length; i++) {
    ScriptApp.deleteTrigger(triggers[i]);
  }

}

function autoArchive() {

  var age = new Date();  
  age.setDate(age.getDate() - AUTO_ARCHIVE_AFTER);

  var auto  = Utilities.formatDate(age, Session.getScriptTimeZone(), "yyyy-MM-dd");
  var search = "in:inbox is:read before:" + auto;

  try {

    var threads = GmailApp.search(search, 0, 100);
    console.log("Found total:", threads.length); //This gives me 100 for the debug/test run which matches the result I should be getting


    if (threads.length == 100) {
      ScriptApp.newTrigger("autoArchive")
               .timeBased()
               .at(new Date((new Date()).getTime() + 1000*60*10))
               .create();
    }

    for (var i=0; i<threads.length; i++) {
      if(threads[i].isInInbox()){
        console.log("So far so good. Let's add label")
        threads[i].addLabel('archived'); // This throws back the error **InternalError: Cannot find method addLabel(string).**
      }
    }

  } catch (e) {
    console.log('Error');
    console.log(e);
  }

}
Run Code Online (Sandbox Code Playgroud)

Tan*_*ike 5

这个改装怎么样?

改装要点:

  • 键入labeladdLabel(label)IS GmailLabel
    • 在您的情况下,您可以使用 的方法getUserLabelByName()

修改后的脚本:

请修改如下。

从:
for (var i=0; i<threads.length; i++) {
  if(threads[i].isInInbox()){
    console.log("So far so good. Let's add label")
    threads[i].addLabel('archived'); // This throws back the error **InternalError: Cannot find method addLabel(string).**
  }
}
Run Code Online (Sandbox Code Playgroud) 到:
var label = GmailApp.getUserLabelByName("archived"); // Added
for (var i=0; i<threads.length; i++) {
  if(threads[i].isInInbox()){
    console.log("So far so good. Let's add label")
    threads[i].addLabel(label); // Modified
  }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 如果您想提供新标签,请在运行脚本之前创建标签。当然,您可以使用脚本创建新标签。当时,请使用方法createLabel()@Cooper的评论。

参考:

如果我误解了你的问题,请告诉我。我想修改它。