Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding the message body from the Gmail API using Go

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:[email protected],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)

    }
  }
}
like image 852
jamesmillerio Avatar asked Feb 19 '16 16:02

jamesmillerio


1 Answers

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?).

like image 178
Cedmundo Avatar answered Oct 16 '22 13:10

Cedmundo