Radek
Radek

Reputation: 11121

Exception: Invalid argument: label

I am new to google scripting. My script goes through desired gmail label parses all emails in all threads. This part works nicely. Now I wanted to add new label to the thread that was just processed. It did not work for me. I found this SO question "Invalid Argument" error with addLabel(label) method but it did not answer the issue.

So I tested it even more and found out that even this code

// Add label MyLabel to the first thread in the inbox
var label = GmailApp.getUserLabelByName("MyLabel");
var firstThread = GmailApp.getInboxThreads(0,1)[0];
firstThread.addLabel(label);

from https://developers.google.com/apps-script/reference/gmail/gmail-thread#addlabellabel

is throwing the same error Exception: Invalid argument: label

Any idea how to add a label to a thread?

UPDATE the label MyLabel does not exist

Upvotes: 1

Views: 1235

Answers (1)

Tanaike
Tanaike

Reputation: 201683

In your script, the existing label name is used. So when new label name, which is not existing, is used, such error occurs. In order to use the new label name, it is required to create new label. So when your script is modified, it becomes as follows.

Modified script:

var newLabelName = "sample1";  // Please set the new label name.
var newLabel = GmailApp.createLabel(newLabelName);
var firstThread = GmailApp.getInboxThreads(0,1)[0];
firstThread.addLabel(newLabel);

Reference:

Added:

About your additional question of how can I check if a label already exists?, I would like to answer. In this case, you can check it using getUserLabelByName. When name of GmailApp.getUserLabelByName(name) is existing, GmailLabel object is returned. When name of GmailApp.getUserLabelByName(name) is NOT existing, null is returned. This can be used. When above script is modified, it becomes as follows.

Modified script:

var newLabelName = "sample1";
var label = GmailApp.getUserLabelByName(newLabelName);
if (!label) {
  label = GmailApp.createLabel(newLabelName);
}
var firstThread = GmailApp.getInboxThreads(0,1)[0];
firstThread.addLabel(label);

Or, as the simple script, you can also use the following script.

var newLabelName = "sample";
var label = GmailApp.getUserLabelByName(newLabelName) || GmailApp.createLabel(newLabelName);
var firstThread = GmailApp.getInboxThreads(0,1)[0];
firstThread.addLabel(label);
  • In this modified script, when newLabelName is not existing, the label is created as new label. When newLabelName is existing, the existing label is used.

Upvotes: 1

Related Questions