Gmail API shows empty body when getting message

736 views Asked by At

When I send a request to get the email body, the Gmail API returns everything but the body data on the payload object.

Things I've tried so far

  • The "Watch" method is already implemented and working fine
  • As you can see from the screenshot, the response shows the "snipped", which means that the message get is working, but the body data and the "raw" field is still empty.
  • I am using the history id correctly (saving the current one to use for subsequent requests)
  • upgrade all the dependencies to the latest stable version

Am I missing anything?

func GetEmail(srv *gmail.Service, historyId uint64) (string, string) {
    hist := getHistory(srv, historyId)

    for _, h := range hist.History {
        for _, m := range h.MessagesAdded {
            id := m.Message.Id
            mailContent, err := srv.Users.Messages.Get("me", id).Format("full").Do()
            if err != nil {
                log.Println("error when getting mail content: ", err)
            }

            if mailContent != nil {
                if mailContent.Payload != nil {
                    payload := mailContent.Payload.Body
                    data, err := b64.RawURLEncoding.DecodeString(payload.Data)
                    if err != nil {
                        log.Println("error b64 decoding: ", err)
                    }
                    body := string(data)

                    if len(body) > 0 {
                        subject := getSubject(mailContent)
                        log.Println("subject ", subject)
                        return body, subject
                    }
                }
            } 
        }
    }

    return "No email to process, something's wrong - GetEmail func", ""
}
1

There are 1 answers

2
Linda Lawton - DaImTo On

If you want the RAW message data then you need to use Format("RAW")

func GetEmail(srv *gmail.Service, messageId string) {

    gmailMessageResposne, err := srv.Users.Messages.Get("me", messageId).Format("RAW").Do()
    if err != nil {
        log.Println("error when getting mail content: ", err)
    }

    if gmailMessageResposne != nil {

        decodedData, err := base64.RawURLEncoding.DecodeString(gmailMessageResposne.Raw)

        if err != nil {
            log.Println("error b64 decoding: ", err)
        }
        fmt.Printf("- %s\n", decodedData)

    }
}

Good question that was fun

How to read a gmail email body with Go?