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;
}