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

huangapple go评论153阅读模式
英文:

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

问题

尝试使用Gmail API(v1)的Go库来获取电子邮件的原始内容,并将其解析为字节切片{[]byte},以便将其保存为电子邮件。有什么建议吗?

英文:

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?

答案1

得分: 2

根据包中的说明,可以使用 rfc822msgId 获取电子邮件。可以从邮件头中获取该值。

gmailMessageResposne, _ := gmail.Service.Users.Messages.Get("user@email.com", "rfc822msgid").Format("RAW").Do()

一旦获得了 *gmail.Message 对象,可以通过以下方式解码原始字符串:

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

然后,使用以下代码将解码后的数据写入文件:

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

这对我起作用了!

英文:

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("user@email.com", "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!

huangapple
  • 本文由 发表于 2022年5月21日 02:25:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/72323346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定