gogoogle-apigmail-apigoogle-api-go-client

Google-api-go-client: listing messages w/ label and fetching header fields


I want to list messages with a specific label. So I used the Go Quickstart code from google and set the scope to gmail.MailGoogleComScope.

Getting a list of all messages with label "INBOX" works fine using this code

    mes, err := srv.Users.Messages.List(user).LabelIds("INBOX").Do()

but when I replace "INBOX" with "TEST" I get the error:

nable to retrieve Messages. googleapi: Error 400: Invalid label: TEST, invalidArgument exit status 1

and there is a label with name TEST. What am I doing wrong?


Solution

  • The label name and ID of "INBOX" are the same. But, there is a case to differ between the label name and label ID. You have 2 methods for retrieving message list of the label. Following scripts suppose the use of Go Quickstart from google.

    1. Check label IDs and retrieve message list

    Retrieve label names and IDs :

    mes, err := srv.Users.Labels.List(user).Do()
    if err != nil {
        log.Fatalf("Error: %v", err)
    }
    for _, e := range mes.Labels {
        fmt.Println(e.Name + ", " + e.Id)
    }
    

    Retrieve message list using labelID :

    mes, err := srv.Users.Messages.List(user).LabelIds(labelID).Do()
    if err != nil {
        log.Fatalf("Error: %v", err)
    }
    for _, e := range mes.Messages {
        fmt.Println(e.Id)
    }
    

    2. Retrieve message list using "Q"

    mes, err := srv.Users.Messages.List(user).Q("label:labelname").Do()
    if err != nil {
        log.Fatalf("Error: %v", err)
    }
    for _, e := range mes.Messages {
        fmt.Println(e.Id)
    }
    

    This can be directly retrieved a message list for the label name. Parameters of "Q" are the same to the Gmail search box.

    References :

    1. Users.messages: list https://developers.google.com/gmail/api/v1/reference/users/messages/list

    2. Users.labels: list https://developers.google.com/gmail/api/v1/reference/users/labels/list