如何在Google App Script中为标签分配标签

时间:2014-07-05 09:24:27

标签: javascript google-apps-script

您好我正在编写一个脚本,将在Gmail上搜索邮件,然后为搜索到的邮件分配标签,但我不知道如何为邮件分配标签,我能够创建标签但我无法分配它。< / p>

另一件事我想知道我是否正确使用Utilities睡眠功能。

    function addNaggingLabels() {
  var label = _getNaggingLabel();

  var start   = parseInt(UserProperties.getProperty("start"));
  var sheet   = SpreadsheetApp.getActiveSheet();
  var ss      = SpreadsheetApp.getActiveSpreadsheet()

  for (;;) {

  // Find all Gmail messages that have attachments
 var threads = GmailApp.search('in:inbox has:attachment larger:15M');

  if (threads.length == 0) {
    ss.toast("Processed " + start + " messages.", "Scanning Done", -1); 
    return;
  }

  for (var i=0; i<threads.length; i++) {

    var messages = threads[i].getMessages();
    UserProperties.setProperty("start", ++start);

    for (var m=0; m<messages.length; m++) {      

      var size = getMessageSize(messages[m].getAttachments());

      if (size>15) {
        Logger.log("label: " + GmailApp.createLabel("FOO"));

      }
}
  }
  }
// Wait for a second to avoid hitting the system limit
  Utilities.sleep(1000);
  return Math.round(size*100/(1024*1024))/100;

}

    function getMessageSize(att) {
  var size = 0;
  for (var i=0; i<att.length; i++) {
    //size += att[i].getBytes().length;
    size += att[i].getSize(); // Better and faster than getBytes()
  }
}

1 个答案:

答案 0 :(得分:5)

您可以使用addLabel方法将标签应用于线程,而不是消息。此外,由于您使用的是较大的搜索运算符,因此稍后无需重新检查附件大小。

var threads = GmailApp.search('in:inbox has:attachment larger:15M');
var label = GmailApp.getUserLabelByName("label name goes here");

for (var t in threads) {
  threads[t].addLabel(label);
}