I'm trying to assign auto-created label to gmail threads. The label alone was successfully created but it couldn't be assigned to the respective threads due to a TypeError.
Here's the script
//call cell value by column (Sheet: "SupplierNumber")
//label created based on the "Label" column in Sheet: SupplierNumber
//Label applied to related threads
function callLabelcolumn()
{
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('SupplierNumber');
var rg=sh.getRange('A2:A');
var vA=rg.getValues();
var sh3 = ss.getSheetByName("SearchParameter")
var rg3=sh3.getRange('A2');
var searchPara =rg3.getValues();
var threads = GmailApp.search(searchPara);
for (var i = 0; i < threads.length; i++){
var msg = threads[i].getMessages();
for (var j = 0; j < msg.length; j++){
// Get same thread by its ID.
//var threadID = GmailApp.getThreadById(msg[j].getId());
var msgid = msg[j].getId();
}
}
vA.forEach(function(row) {
if(row != "" && row != "#N/A"){
Logger.log('Label: %s', row);
var label = GmailApp.createLabel(row);
Logger.log("label: " + label);
}
var thread = [0];
var thread = GmailApp.getMessageById(msgid).getThread().getId();
var name = GmailApp.getUserLabelByName(label.getName())
for(var t in thread){
console.log("So far so good. Let's add label")
thread[t].addLabel(name);
}
});
}
The error is " TypeError: thread[t].addLabel is not a function " when run script in the editor. TypeError: thread[t].addLabel is not a function
After debugging, I'm suspecting var name returned "" or null which is why the error is happening.
Debug result: thread[t].addLabel
I tried debugging on var name, some of results were name: undefined, t: undefined which I think is the cause of the TypeError.
Debug result: var name = GmailApp.getUserLabelByName(label.getName())
So is there a way to solve this?