Inconsistencies between app scripts GmailApp.search and the search in gmail interface

耗尽温柔 提交于 2019-12-13 14:26:16

问题


I'm trying to build a google app script to import mail received from an online form to a spreadsheet.

I am using two labels: One "to_process" is added by a gmail filter, the other one "processed" is added by this script after the email was added to the sheet.
I am searching for all emails that have "to_process" but not "processed" using the search query 'label:to_process !label:processed in:all'

I got it working partially (see the core of the script below)
I'm running the script using the script editor run function.

The problem is that using the same query in gmail interface i get more than 100 emails, but in the log of the script I get 6, and they are all processed. Am I missing something?

function extractInfo() {
  var step = 30;
  var max = 500;
  var currentStep = 0;
  while(max--) {
    var threads = GmailApp.search('label:to_process !label:processed in:all', currentStep++ * step, step);
    if(threads.length == 0) break;
    Logger.log("-------- found threads: " + threads.length);
    var threadId = threads.length;

    while(threadId--) {
      var thread = threads[threadId];
      thread.refresh();
      if(hasLabel(thread, "processed")) {
        Logger.log("was processed: " + thread.getPermalink())
        continue;
      }
      if(!hasLabel(thread, "to_process")) {
        Logger.log("isn't mark to process: " + thread.getPermalink())
        continue;
      }
      var messages = thread.getMessages(); 
      var messageId = messages.length;
      while(messageId--) {
        var message = messages[messageId];
        var row = extractMessageData(message);
        sheet.appendRow(row);
        GmailApp.markMessageRead(message);
      }
      threads[threadId].addLabel(processedLabel);
    }
  }
}

function hasLabel(thread, name) {
  var labels = thread.getLabels();
  var l = labels.length;
  while(l--) {
    if(labels[l].getName() == name) {
      return true;
    }
  }
  return false;
}

回答1:


After much trail and error I partially figured this out.

What I see in gmail ui is in fact message, and not threads. But handling labels is a per thread thing. I simply pulled all message of all threads from a given label, and then processed theses.

If a thread has a label "processed" it doesn't mean all it's messages were processed, which is a problem.

There are still inconsistencies regarding the number of messages i see in the UI and what I get using the API though.



来源:https://stackoverflow.com/questions/31261134/inconsistencies-between-app-scripts-gmailapp-search-and-the-search-in-gmail-inte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!