一旦使用net/mail解析了邮件并获得了Message,如果正文是quoted-printable编码的(Content-Transfer-Encoding: quoted-printable
):
示例:
r := quotedprintable.NewReader(msg.Body)
body, err := ioutil.ReadAll(r) // body now contains the decoded body
Content-Transfer-Encoding: base64
),则应使用encoding/base64 package。我曾经使用github.com/jhillyerd/enmime成功地将头部和正文分离出来。只需要提供一个io.Reader
r
:
// Parse message body
env, _ := enmime.ReadEnvelope(r)
// Headers can be retrieved via Envelope.GetHeader(name).
fmt.Printf("From: %v\n", env.GetHeader("From"))
// Address-type headers can be parsed into a list of decoded mail.Address structs.
alist, _ := env.AddressList("To")
for _, addr := range alist {
fmt.Printf("To: %s <%s>\n", addr.Name, addr.Address)
}
fmt.Printf("Subject: %v\n", env.GetHeader("Subject"))
// The plain text body is available as mime.Text.
fmt.Printf("Text Body: %v chars\n", len(env.Text))
// The HTML body is stored in mime.HTML.
fmt.Printf("HTML Body: %v chars\n", len(env.HTML))
// mime.Inlines is a slice of inlined attacments.
fmt.Printf("Inlines: %v\n", len(env.Inlines))
// mime.Attachments contains the non-inline attachments.
fmt.Printf("Attachments: %v\n", len(env.Attachments))
artagnon/ibex
这样使用 go-imap
package 的项目是否提供该功能。artagnon/ibex/imap.go#L288-L301
测试。var body []byte
cmd, err = imap.Wait(c.UIDFetch(set, "BODY.PEEK[]"))
if (err != nil) {
fmt.Println(err.Error())
return nil
}
body = imap.AsBytes(cmd.Data[0].MessageInfo().Attrs["BODY[]"])
cmd.Data = nil
bytestring, err := json.Marshal(MessageDetail{string(body)})
if (err != nil) {
fmt.Println(err.Error())
return nil
}
return bytestring