Search code examples
google-apps-scriptgmail

Gmail's Apps script, assigning inbox label to thread


When I want to give a thread a user defined label, there is no problem. But problems start when I want to give just the system label "Inbox".

label = GmailApp.getUserLabelByName("Inbox")

thread.addLabel(label)

I get this error:

Invalid argument: label (line 2, file 'Code')


Solution

  • In Gmail, "inbox" is a system label that, unlike user-created labels, is not accessible through the getLabels() method of the GmailThread class.

    Note that if you log into your Gmail account and type in "label: inbox" into the search bar, it will return the list of threads with the visual label "inbox" applied to them.

    For security reasons, you can only interact with system labels like "inbox" or "spam" using the methods that Google wrapped around them. In the following example, the result is the same as applying the "inbox" label to a thread:

          var thread = GmailApp.getThreadById("yourId");
    
          if(!thread.isInInbox()) {
    
                thread.moveToInbox(); //apply the inbox label
    
                       }
    

    You can also filter inbox messages by using the search() method of the GmailApp class:

        var threads = GmailApp.search("label: inbox from: [email protected]");
    

    Hope this helps!