使用 Go 从 Gmail API 解码邮件正文
Decoding the message body from the Gmail API using Go
我正在尝试使用 Go 中的 Gmail API 检索邮件的完整邮件正文。目前,当我这样做时,我只能得到消息正文的前三个字符“
我看过其他几种语言的示例,并尝试将它们翻译成 Go,但没有成功。编码后的消息正文相当大,所以我很确定某些数据在某处丢失了。
这是一个(删节的)代码片段,说明了我一直在尝试如何解决这个问题:
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)
}
}
}
需要使用 Base64 URL 编码(字母表与标准 Base64 编码略有不同)。
使用相同的 base64
包,您应该使用:
base64.URLEncoding.DecodeString
而不是
base64.StdEncoding.DecodeString
.
要从标准 Base64 获取 URL Base64,请替换:
+ to - (char 62, plus to dash)
/ to _ (char 63, slash to underscore)
= to * padding
来自正文字符串(来源:Base64 decoding of MIME email not working (GMail API) and here: How to send a message successfully using the new Gmail REST API?)。
我正在尝试使用 Go 中的 Gmail API 检索邮件的完整邮件正文。目前,当我这样做时,我只能得到消息正文的前三个字符“ 我看过其他几种语言的示例,并尝试将它们翻译成 Go,但没有成功。编码后的消息正文相当大,所以我很确定某些数据在某处丢失了。 这是一个(删节的)代码片段,说明了我一直在尝试如何解决这个问题: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)
}
}
}
需要使用 Base64 URL 编码(字母表与标准 Base64 编码略有不同)。
使用相同的 base64
包,您应该使用:
base64.URLEncoding.DecodeString
而不是
base64.StdEncoding.DecodeString
.
要从标准 Base64 获取 URL Base64,请替换:
+ to - (char 62, plus to dash)
/ to _ (char 63, slash to underscore)
= to * padding
来自正文字符串(来源:Base64 decoding of MIME email not working (GMail API) and here: How to send a message successfully using the new Gmail REST API?)。