卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

使用 net/mail 解析电子邮件

使用 net/mail 解析电子邮件

问题内容

我目前正在 golang 中使用 net/mail 解析电子邮件。

import (
  "net/mail"
  "io"
  "strings"
)

func main() {
  email := "some email received"

  reader := strings.newreader(emailinput)
  msg, err := mail.readmessage(inputreader)
  check(err)

  body, err := io.readall(msg.body)
  check(err)

  fmt.println(string(body))
}

这对于纯文本电子邮件来说效果很好。但是,当我使用包含 html 的 apple mail 应用程序发送电子邮件时,返回了以下正文:

--Apple-Mail=3D_4A1E75FB-9514-439D-B922-8526851CA743
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
    charset=3Dus-ascii

fn main() {
  println!("Hello world!");
}


--Apple-Mail=3D_4A1E75FB-9514-439D-B922-8526851CA743
Content-Transfer-Encoding: 7bit
Content-Type: text/html;
    charset=3Dus-ascii

<html><head><meta http-equiv=3D"Content-Type" content=3D"text/html; charset=
=3Dus-ascii"></head><body style=3D"word-wrap: break-word; -webkit-nbsp-mode=
: space; line-break: after-white-space;" class=3D"">
fn <span cl=
ass=3D"" style=3D"color: rgb(230, 97, 112); font-weight: bold;">main</span>=
<span class=3D"" style=3D"color: rgb(210, 205, 134);">(</span><span class=
=3D"" style=3D"color: rgb(210, 205, 134);">)</span> <span class=3D"" style=
=3D"color: rgb(176, 96, 176);">{</span>
  println<span class=3D"" style=3D"color: rgb(210, 205, 134);">!</span><spa=
n class=3D"" style=3D"color: rgb(210, 205, 134);">(</span><span class=3D"" =
style=3D"color: rgb(2, 208, 69);">"</span><span class=3D"" style=3D"color: =
rgb(0, 196, 196);">Hello world!</span><span class=3D"" style=3D"color: rgb(=
2, 208, 69);">"</span><span class=3D"" style=3D"color: rgb(210, 205, 134);"=
>)</span><span class=3D"" style=3D"color: rgb(176, 96, 176);">;</span>
<span class=3D"" style=3D"color: rgb(176, 96, 176);">}</span>

3D"" --Apple-Mail=3D_4A1E75FB-9514-439D-B922-8526851CA743--

当使用 sendgrid 将此正文发送给我自己时,我收到以下电子邮件:

附件也会发生类似的情况。如何正确解析此电子邮件以便我可以将其再次发送到另一个电子邮件地址?


正确答案


如果您想在另一封邮件中重用邮件内容(例如重定向),仅包含正文是不够的,还需要包含邮件标头。

具体来说,您至少需要包含原始 Content-Type 标头,该标头显示应如何解释正文。在您的情况下,它包含一些 multipart/* 内容类型(即诸如 multipart/mixed、multipart/related、multipart/alternative 之类的东西)以及分隔邮件正文中各部分的边界。如果这不是多部分正文,则 Content-Type 包含字符集,该字符集确定使用的文本编码,即 utf-8、iso-8859-15,...

对于非多部分正文,您还需要包含原始 Content-Transfer-Encoding 标头,该标头确定正文如何编码以进行传输,即 base64、quoted-printable、7bit,...

卓越飞翔博客
上一篇: 从 cobra 子命令检索的上下文为空
下一篇: 尝试写入/读取时 io.Pipe 和死锁
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏