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?
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.
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)
}
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 :
Users.messages: list https://developers.google.com/gmail/api/v1/reference/users/messages/list
Users.labels: list https://developers.google.com/gmail/api/v1/reference/users/labels/list