首页 > 后端开发 > Golang > 正文

使用 net/mail 解析电子邮件

WBOY
发布: 2024-02-06 09:40:07
转载
825 人浏览过

使用 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""><pre class=3D"" style=
=3D"color: rgb(209, 209, 209); background-color: rgb(0, 0, 0);">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,...

以上是使用 net/mail 解析电子邮件的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!