0
votes

I have a filter that adds the "unprocessed" label on all incoming emails.

Then a Google Script searches every minute for any email threads that have the "unprocessed" label, processes the messages, and conditionally apply a label to the corresponding thread.

I don't know what I have done wrong, but only SOME of the processed threads get the label. And it works randomly... For example only 3 out of 6 threads got the label, or 1 out of 3.

I have to re-apply the "unprocessed" label, and just run the script again to fix them.

function processGmail() {
  var startTime = new Date().getTime();
  var mailerRegex = /X-Mailer:(.*)/g;
  var scannerLabel = GmailApp.getUserLabelByName("Scanner");
  var unprocessedLabel = GmailApp.getUserLabelByName("unprocessed");
  var countMessages = 0;

  GmailApp.search("label:unprocessed").forEach(
    function(emailThread) {

      emailThread.getMessages().forEach(
        function(message) {

          var raw = message.getRawContent();
          var result;
          var doReturn = false;

          while((matches = mailerRegex.exec(raw)) !== null) { 
            if (matches.some(function(match){return match.indexOf('Canon MFP') >= 0;})) {
              emailThread.addLabel(scannerLabel);
              emailThread.moveToArchive();
              doReturn = true;
              break;
            }
          }

          emailThread.removeLabel(unprocessedLabel);
          ++countMessages;

          if (doReturn) {
            return;
          }
        }
      );
    }
  );

  var endTime = new Date().getTime();
  Logger.log("Processed " + countMessages + " in " + (endTime-startTime) + "ms.");
}
1
Make sure you write back to Gmail that the messages have changed, e.g. refresh them? See stackoverflow.com/questions/49540711/…tehhowch
Thanks for the reference. It doesn't seem to have helped the OP :/Stefanos Kalantzis

1 Answers

1
votes

Turns out the bug was Javascript related.

I had forgotten that the regex.exec needs to be looped until a null is returned, only then it will start a-new for a new input.

The fix was removing break :)