RamelHenderson
RamelHenderson

Reputation: 2371

How can I download an Email using the Gmail api with Go

Trying to use the Go library of the Gmail API (v1) to get the raw content of a email and parse it as a byte slice {[]byte} so I can save it as an email. Any tips?

Upvotes: 2

Views: 1283

Answers (1)

RamelHenderson
RamelHenderson

Reputation: 2371

Looking at the package (https://pkg.go.dev/google.golang.org/api/gmail/v1#Message) it states:

// Raw: The entire email message in an RFC 2822 formatted and base64url
// encoded string. Returned in `messages.get` and `drafts.get` responses
// when the `format=RAW` parameter is supplied.

Get the email using the rfc822msgId. This can be grabbed from the header.

gmailMessageResposne, _ := gmail.Service.Users.Messages.Get("[email protected]", "rfc822msgid").Format("RAW").Do() 

Once you have the *gmail.Message object you can decode the raw string via

decodedData, _ := base64.URLEncoding.DecodeString(gmailMessageResposne.Raw)

Then

base64.URLEncoding(decodedData, decodedData)

Finally

ioutile.WriteFile("message.eml", decodedData, os.ModePerm)

This worked for me!

Upvotes: 2

Related Questions