Using google script for google mail, I'm trying to upload new emails with certain labels to our CRM using an API. I can't check if messages have been uploaded already, so I have to apply a label in the mailbox to messages that have been processed before.
Unfortunately, google script only lets you add or check labels on a thread level. Since new messages can come in for a thread after it has last been uploaded to the CRM, I don't know what messages of a thread have actually been processed already.
The Code below contains what I had in mind, the function getLabels does not work for Message however so it does not work.
Hope somebody has a smart solution!
Thanks
//execute main sequence
function collecttobesend() {
var labeladd = GmailApp.getUserLabelByName("add to CRM");
var labeladded = GmailApp.getUserLabelByName("added to CRM");
//var threads = label.getThreads();
var threads = GmailApp.search('label:added-to-crm -label:add-to-crm')
for (var i = 0; i < threads.length; i++) {
thread = threads[i];
// get all messages in a given thread
var messages = thread.getMessages();
// iterate over each message
for (var j = 0; j < messages.length; j++) {
message = messages[j];
var labels = message.getLabels();
var messagehaslabeladded = false;
for (var k = 0; k < labels.length; k++) {
if (labels[k] = labeladded) {
messagehaslabeladded = true;
}
}
// if message has not been added yet
if (messagehaslabeladded = false) {
var success = false;
//add to CRM through API
success = true;
//if succesfull add label
if (success = true) {
message.addLabel(labeladded);
}
}
}
}