已經在 ptt 的 PHP 提供了這個資訊,我覺得還不錯,畢竟看到大家都有這個問題
mail 這個函式在官網提供很多範例,其實都還不錯,不過個人很推 PEAR - PHP Mail and Mail_Mime
可以參考
[PHP] 好用的 PEAR - PHP Mail and Mail_Mime
http://blog.wu-boy.com/2007/12/18/129/[PHP]解決 PEAR::Mail_Mime 標題 UTF-8 亂碼問題(不能顯示)
http://blog.wu-boy.com/2008/10/01/524/接下來就是介紹怎麼安裝了,首先你的系統要有搭配 php pear 的套件
cd /usr/ports/devel/pear
make install
不過你如果裝 php5 的套件的話,她會順便一起裝進去,我想這不是重點
再來就是下載 PEAR::Mail 跟 PEAR::Mail_Mime 套件
其實作法很簡單,就是下載程式都丟到 includes 裡面,然後要用到的時候,利用底下
define('Document_root',dirname(__FILE__));
這個相當好用,取得絕對路徑,之後只要寫成下面底下就好
include(Document_root . '/includes/Mail.php');
include(Document_root . '/includes/Mail/mime.php');
再來是最普通的寄送範例:
include(Document_root . '/includes/Mail.php');
$recipients = 'joe@example.com';
$headers['From'] = 'richard@phpguru.org';
$headers['To'] = 'joe@example.com';
$headers['Subject'] = 'Test message';
$body = 'Test message';
$mail_object =& Mail::factory('mail');
$mail_object->send($recipients, $headers, $body);
裡面有一行
$mail_object =& Mail::factory('mail');
這個有三種方式 mail, sendmail, smtp
mail: 這是不需要任何參數的
sendmail:需要 sendmail 的程式路徑跟她所需要的參數
smtp:需要 mail 主機位址,port,是否需要認證,帳號密碼之類的
當然我們用最普通的就好,那就是 mail 就可以,不過前提你要先架好 mail Server
Mail_Mime 的部分:
這部份比較複雜,我們先看範例:
include(Document_root . '/includes/Mail.php');
include(Document_root . '/includes/Mail/mime.php');
$text = '我是小惡魔我是小惡魔我是小惡魔我是小惡魔';
$html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Hello World!</title>
</head>
<body>
<p>Hello World!</p>
<p>我是小惡魔</p>
<p>我是小惡魔</p>
<p>我是小惡魔</p>
<p>我是小惡魔</p>
</body>
</html>';
$file = '/home/appleboy/adwii/AB2.jpg';
$crlf = "\n";
$param['text_charset'] = 'utf-8';
$param['html_charset'] = 'utf-8';
$param['head_charset'] = 'utf-8';
$hdrs = array(
'From' => 'appleboy@example.org',
'Subject' => '系統資訊',
'Content-type' => 'text/plain; charset=utf-8'
);
$mime = new Mail_mime($crlf);
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text/plain', 'AB2.jpg');
$body = $mime->get($param);
$hdrs = $mime->headers($hdrs);
//echo $body;
$mail =& Mail::factory('mail');
$mail->send('appleboy@example.org', $hdrs, $body);
這個範例,可以附加檔案,跟寫 html 格式的 mail 寄信到對方
$mime->addAttachment($file, 'text/plain', 'AB2.jpg');
這一行就是寄送附加檔案,附加檔案的格式如下
function addAttachment($file,
$c_type = 'application/octet-stream',
$name = '',
$isfile = true,
$encoding = 'base64',
$disposition = 'attachment',
$charset = '',
$language = '',
$location = '')
1.使用 Mail_mime() 建立新的 Mail_mime 物件(constructor)。
2.至少要使用 setTXTBody(), setHTMLBody(), addHTMLImage() 或 addAttachment()
四者其中之一建立內文或附檔。(當然通常的情況不只使用一個囉)
3.使用 get() 傳回內文。
4.使用 headers() 傳回檔頭。
5.利用傳回的內文與檔頭丟給 Mail::send() 送信。
reference
http://pear.php.net/manual/en/package.mail.mail.intro.phphttp://blog.xuite.net/noi1/yamesz/8928129http://pear.php.net/manual/en/package.mail.mail-mime.example.php