1

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

1 Answer 1

0

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?

2
  • Great article, that was helpful. I was trying to get the body from the payload, not the raw email. For some reason it comes empty. Anyway, if I can't find out why its payload body is empty, I think I will have to use raw. Dec 14, 2022 at 22:39
  • This is what I normally use in other languages. If i get board i will play around with pay load, I did have fun working that out. Dec 15, 2022 at 7:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.