心在冰

导航

使用sendmail发送邮件

转自:http://www.cnblogs.com/web-backend/archive/2010/04/16/1713444.html

 

 sendmail是linux/unix系统下用来发送邮件的客户端。sendmail使用SMTP协议将邮件发送到目的SMTP服务器。其工作流程大概如下:

    首先要说一下DNS的MX记录:SMTP服务器基于DNS中的MX(mail exchange)记录来路由电子邮件,MX记录注册了域名和相关的SMTP中继主机,属于该域的电子邮件都应向该主机发送。 

   (1)Sendmail 请求DNS给出主机sh.abc.com的CNAME 记录,如有,假若CNAME(别名记录)到shmail.abc.com,则再次请求shmail.abc.com的CNAME记录,直到没有为止。
   (2)假定被CNAME到shmail.abc.com,然后sendmail请求@abc.com 域的DNS给出shmail.abc.com的MX记录(邮件路由及记录),shmail MX 5 shmail.abc.com 10 shmail2.abc.com。
   (3)Sendmail组合请求DNS给出shmail.abc.com的A记录(主机名(或域名)对应的IP地址记录),即IP地址,若返回值为10.0.0.4(假设值)。
   (4)Sendmail与10.0.0.4连接,传送这封给user@sh.abc.com 的信到1.2.3.4 这台服务器的SMTP后台程序。 

 

1. 构造邮件

    在使用sendmail发送邮件之前,首先需要按邮件格式构造一封邮件。包括邮件头,邮件消息体。邮件格式在RFC5322:internet message format(http://tools.ietf.org/html/rfc5322)中有详细说明。

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->From: John Doe <jdoe@machine.example>

Sender: Michael Jones <mjones@machine.example>

To: Mary Smith <mary@example.net>

Subject: Saying Hello

Date: Fri, 21 Nov 1997 09:55:06 -0600

Message-ID: <1234@local.machine.example>



This is a message just to say hello.

So, "Hello".

  

可以暂不指定date头(邮件发送时间)和messageid,这个信息将由sendmail程序填写。

 

 

2. 使用sendmail发送邮件

    将邮件构造好之后,保存到一个本地文件,如/data/mail_content。然后调用sendmail发送,发送时指定接收邮箱地址:

    cat /data/mail_content | sendmail user@163.com 

 

3. 发送HTML格式的邮件

    如果要发送html格式的邮件, 就是说,邮件的消息体为一个html文件,需要在邮件头中指定 content-type为 text/html。如果不指定,默认情况下,content-type为text/plain,即普通文本。 

 

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->From: John Doe <jdoe@machine.example>
Sender: Michael Jones <mjones@machine.example>
To: Mary Smith <mary@example.net>
Content-type: text/html
Subject: Saying Hello

<div style="border:solid 1px #1D448C;">
<h1>This is a message just to say hello.</h1>
<p>So, "Hello".</p>
</div>

4. 字符编码

    在发送中文邮件中,字符编码是一个比较重要的问题,如果设置不正确,会导致邮件标题或邮件内容显示乱码。

 

    邮件内容的编码可以在邮件头content-type中设置,如设置邮件内容为utf-8编码:

    Content-type: text/html;charset=utf-8

    

    邮件头中,如From,To,Subject等,如果需要用到中文,可以这样设置:

    =?UTF-8?B?”+base64encode(内容UTF8编码)+"?=" 

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->From: =?UTF-8?B?5L2g5aW9?= <jdoe@machine.example>
Sender: Michael Jones <mjones@machine.example>
To: Mary Smith <mary@example.net>
Content-type: text/html;charset=utf-8
Subject: =?UTF-8?B?5L2g5aW9?=

<div style="border:solid 1px #1D448C;">
<h1>This is a message just to say hello.</h1>
<p>So, "Hello".</p>
</div>



posted on 2012-03-25 19:01  心在冰  阅读(5681)  评论(0编辑  收藏  举报