PHP mail() 函數雖簡單,但要正常運作需正確配置 SMTP 服務器。本文詳細講解 SMTP 原理、Windows/Linux 下的 php.ini 配置、郵件頭構建、批量發送及文本/HTML 多格式郵件發送。
SMTP (Simple Mail Transfer Protocol) 是郵件傳輸協議。常見 SMTP 服務器軟件:Linux 下的 Sendmail、Qmail;Windows 下內建的 SMTP 服務(NT Service Pack / Win2000)。若本機無 SMTP,可使用 ISP 提供的外發郵件服務器(如 mail.earthlink.net)。
sendmail_path = /usr/sbin/sendmail -t -f you@yourdomain.com
SMTP = mail.earthlink.net ; 或 localhost(若本機裝有 SMTP 服務)
sendmail_from = youraddress@yourdomain.com
修改後必須重啟 Web 服務器,用 phpinfo() 驗證生效。
mail(to, subject, message, additional_headers, additional_parameters)
to:收件人地址subject:主題message:郵件正文additional_headers(可選):From、Cc、Bcc、Reply-To 等additional_parameters(可選):傳遞給 sendmail 的額外參數<?php
$to = "user@example.com";
$subject = "測試郵件";
$boundary = md5(time());
$headers = "From: Sender <sender@example.com>\r\n";
$headers .= "Reply-To: reply@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n\r\n";
$message = "--$boundary\r\n";
$message .= "Content-Type: text/plain; charset=utf-8\r\n\r\n";
$message .= "這是純文本內容,給不支援 HTML 的客戶端。\r\n\r\n";
$message .= "--$boundary\r\n";
$message .= "Content-Type: text/html; charset=utf-8\r\n\r\n";
$message .= "<h1>這是 HTML 內容</h1><p>支持富文本顯示。</p>\r\n\r\n";
$message .= "--$boundary--";
mail($to, $subject, $message, $headers);
?>
php.ini 設定是否正確、防火牆是否阻擋。charset=utf-8,正文編碼為 UTF-8。