Search code examples
javascriptgoogle-apps-scriptgmail

Add label to emails in Gmail fails


We are trying to add a Label in Gmail to Threads. Both var's put the same output "2014/October/Sent" But only SentLabel2 Works, if we set SentLabel threads[i].addLabel(SentLabel); it fail's.

We need it to be SentLabel beacuse we have done a auto-month thing like this (that gets the curent month, this way we dont need to manually go in to the script every month and change the variable):

  var SentLabel = "2014/" + monthInWords[d.getMonth()] + "/Sent";

Here is what it looks like now:

 function wtf2() {
        var SentLabel = "2014/October/Sent";
        var SentLabel2 = GmailApp.getUserLabelByName("2014/October/Sent");


      var threads = GmailApp.getInboxThreads(0, 5);
      for (var i = 0; i < threads.length; i++) {
        var labels = threads[i].getLabels()[0];          
     threads[i].addLabel(SentLabel);

    }
    }

Solution

  • The reason why your statement below fails is because SentLabel is a string variable, not a gmailLabel variable.

    threads[i].addLabel(SentLabel);

    To fix this you'll want to conditionally create a gmailLabel variable (i'll call this var label) depending on if it already exists. Here's how you can do it:

     var label = GmailApp.getUserLabelByName(SentLabel);  //declares a variable called label and initializes it to be the value thats returned when searching GmailApp for any label that is named the same as the string you provided in your SentLabel variable
    
        if (label) { //if gmail finds a matching label
          Logger.log('Label exists.');
        } else {
          Logger.log('Label does not exist. Creating it.');
          label = GmailApp.createLabel(SentLabel);
        }
    

    Once this runs then you'll have a label variable and then your statement will work if you change it to this:

    threads[i].addLabel(label);
    

    You can read about the GmailLabel class here, https://developers.google.com/apps-script/reference/gmail/gmail-label#