萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 發送郵件完整指南:從 SMTP 配置到 mail() 實戰

前言

PHP mail() 函數雖簡單,但要正常運作需正確配置 SMTP 服務器。本文詳細講解 SMTP 原理、Windows/Linux 下的 php.ini 配置、郵件頭構建、批量發送及文本/HTML 多格式郵件發送。

SMTP 基礎

SMTP (Simple Mail Transfer Protocol) 是郵件傳輸協議。常見 SMTP 服務器軟件:Linux 下的 Sendmail、Qmail;Windows 下內建的 SMTP 服務(NT Service Pack / Win2000)。若本機無 SMTP,可使用 ISP 提供的外發郵件服務器(如 mail.earthlink.net)。

php.ini 關鍵配置

Linux/Unix

sendmail_path = /usr/sbin/sendmail -t -f you@yourdomain.com

Windows

SMTP = mail.earthlink.net ; 或 localhost(若本機裝有 SMTP 服務)
sendmail_from = youraddress@yourdomain.com

修改後必須重啟 Web 服務器,用 phpinfo() 驗證生效。

mail() 函數詳解

mail(to, subject, message, additional_headers, additional_parameters)
  • to:收件人地址
  • subject:主題
  • message:郵件正文
  • additional_headers(可選):From、Cc、Bcc、Reply-To 等
  • additional_parameters(可選):傳遞給 sendmail 的額外參數

實戰:發送帶 HTML 與純文本備選的郵件

<?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);
?>

常見問題排查

  • 郵件發不出去:檢查 SMTP 服務器是否可連通(telnet 25 端口)、php.ini 設定是否正確、防火牆是否阻擋。
  • 進垃圾箱:設置有效的 SPF/DKIM、避免垃圾郵件關鍵詞、使用可信域名發送。
  • 中文亂碼:郵件頭聲明 charset=utf-8,正文編碼為 UTF-8。
copyright © 萬盛學電腦網 all rights reserved