ITeye博客

shell发送包含图片的邮件

unbounder · 2011-07-14 17:26 · shell · 编程语言 · Markdown

用shell 发封html格式的邮件不难 cat mail|sendmail -t 其中mail为 To:xx@111.com Subject:aaa content-type:text/html

但是如果想在邮件正文中嵌入附件图片: (cat mail;uuencode a.jpg a.jpg)|sendmail -t To:xx@111.com Subject:aaa content-type:text/html

那怎么办呢?

先来了解mime的概念,MIME的英文全称是"Multipurpose Internet Mail Extensions" 多功能Internet 邮件扩充服务,它是一种多用途网际邮件扩充协议 http://en.wikipedia.org/wiki/MIME 一封嵌入附件中的图片的邮件,就得符合mime协议。

按照rcf2046中所说 http://tools.ietf.org/html/rfc2046#section-5.1.1 当邮件中需要一个图片附件时的格式为:

MIME-Version: 1.0 Content-type: multipart/mixed; boundary="123"

 This is the preamble.  It is to be ignored, though it
 is a handy place for composition agents to include an
 explanatory note to non-MIME conformant readers.

--123 Content-Type: image/jpeg; name=a.jpg Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=a.jpg;

a.jpg的base64数据

--123--

而一个内容为html的邮件格式为:

MIME-Version: 1.0 Content-type: multipart/mixed; boundary="123"

 This is the preamble.  It is to be ignored, though it
 is a handy place for composition agents to include an
 explanatory note to non-MIME conformant readers.

--123 Content-Type: text/html; charset=gbk; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline

html代码

--123--

组合一下,

MIME-Version: 1.0 Content-type: multipart/mixed; boundary="123"

 This is the preamble.  It is to be ignored, though it
 is a handy place for composition agents to include an
 explanatory note to non-MIME conformant readers.

--123 Content-Type: text/html; charset=gbk; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline

html代码

Content-Type: image/jpeg; name=a.jpg Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=a.jpg;

a.jpg的base64数据 --123--

邮件格式中的换行是协议需求,不能省去。 注意 1 获取某种图片的base64编码的方法为cat a.jpg |uuencode --base64 a.jpg>temp 2 得到a.jpg的编码后,要通过sed命令来去掉第一行和最后一行。因为第一行是begin base64 xxxx,最后一行是==== 3 html代码里获取附件的方法是 4 附件格式和content-type的对应关系查看http://www.webmaster-toolkit.com/mime-types.shtml

上面的片段再加上邮件头部,得到文件mail 然后使用cat mail|sendmail -t就可以发送包含图片的邮件了。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。