使用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>




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM