6

I'm attempting to retrieve the full message body of messages using the Gmail API in Go. Currently when I do so, I only get the first three characters of the message body which are "<ht". I'm pretty sure my issue lies with the decoding of the message body but I can't seem to figure out what I'm doing wrong.

I've looked at examples in several other languages and have tried to translate them to Go with no success. The encoded message body is rather large so I'm fairly certain some data is getting lost somewhere.

Here is an (abridged) code snippet illustrating how I've been attempting to go about this:

req := svc.Users.Messages.List("me").Q("from:someone@somedomain.com,label:inbox")

r, _ := req.Do()

for _, m := range r.Messages {

  msg, _ := svc.Users.Messages.Get("me", m.Id).Format("full").Do()

  for _, part := range msg.Payload.Parts {

    if part.MimeType == "text/html" {

      data, _ := base64.StdEncoding.DecodeString(part.Body.Data)
      html := string(data)
      fmt.Println(html)

    }
  }
}
jamesmillerio
  • 3,154
  • 4
  • 27
  • 32

1 Answers1

10

Need to use Base64 URL encoding (slightly different alphabet than standard Base64 encoding).

Using the same base64 package, you should use:
base64.URLEncoding.DecodeString instead of base64.StdEncoding.DecodeString.

To get URL Base64 from standard Base64, replace:

+ to - (char 62, plus to dash)
/ to _ (char 63, slash to underscore)
= to * padding

from body string (source here: Base64 decoding of MIME email not working (GMail API) and here: How to send a message successfully using the new Gmail REST API?).

Lix
  • 47,311
  • 12
  • 103
  • 131
Cedmundo
  • 682
  • 4
  • 12
  • 1
    I read that first link at least 5 times before posting and then realized my issue as soon as I saw your post. It's not actually replacing those characters that's the issue. It's using base64.StdEncoding instead of base64.URLEncoding. Thanks for pointing me in that direction. – jamesmillerio Feb 19 '16 at 18:50