PHP 內建 mail() 功能極簡、無 SMTP 驗證、無附件支援、編碼處理弱。PHPMailer 是功能最完整、社群最活躍的 PHP 郵件庫,已成為 Laravel、Symfony、Yii 等框架的預設郵件元件。
| 功能 | 支援 | 備註 |
|---|---|---|
| SMTP 驗證 (AUTH LOGIN/PLAIN/CRAM-MD5/XOAUTH2) | ✅ | 支援 Gmail、Outlook、企業郵箱 |
| 多收件人 (To/CC/BCC/Reply-To) | ✅ | |
| HTML + 純文字替代內容 | ✅ | AltBody 自動生成或手動指定 |
| 內嵌圖片 (CID) | ✅ | addEmbeddedImage() |
| 多附件 (檔案/字串/二進位) | ✅ | addAttachment()/addStringAttachment() |
| 編碼支援 | ✅ | 8bit, base64, quoted-printable, binary |
| SSL/TLS (SMTPS / STARTTLS) | ✅ | SMTPSecure = 'ssl'/'tls' |
| 多語言錯誤訊息 | ✅ | 內建 40+ 語系 |
| DKIM 簽名 | ✅ | v6.0+ |
| 異步/隊列發送 | 🔧 | 需自行結合隊列系統 |
composer require phpmailer/phpmailer
從 GitHub Releases 下載,只需 src/PHPMailer.php、src/SMTP.php、src/Exception.php 三個檔案。
<?php
require 'vendor/autoload.php'; // Composer
// require 'src/PHPMailer.php'; // 手動
// require 'src/SMTP.php';
// require 'src/Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
function sendMail(string $to, string $subject, string $htmlBody, array $attachments = []): bool {
$mail = new PHPMailer(true); // true = 啟用異常拋出
try {
// === SMTP 設定 ===
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@gmail.com'; // 完整 Gmail 地址
$mail->Password = 'your_app_password'; // 應用程式密碼(非登入密碼)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // 'ssl',465 port
$mail->Port = 465;
// === 發件人/收件人 ===
$mail->setFrom('your@gmail.com', '您的名稱');
$mail->addAddress($to);
$mail->addReplyTo('reply@example.com', '回覆名稱'); // 可選
// === 內容 ===
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $htmlBody;
$mail->AltBody = strip_tags($htmlBody); // 純文字備用
// === 附件 ===
foreach ($attachments as $path => $name) {
$mail->addAttachment($path, $name);
}
// === 除錯(僅開發環境)===
// $mail->SMTPDebug = SMTP::DEBUG_SERVER; // 2 = 完整對話
// $mail->Debugoutput = function($str, $level) { error_log("PHPMailer [$level]: $str"); };
$mail->send();
return true;
} catch (Exception $e) {
error_log("郵件發送失敗: {$mail->ErrorInfo}");
return false;
}
}
// 使用範例
sendMail(
'target@example.com',
'測試主題',
'HTML 內容
支援 粗體、連結、中文。
',
['/path/to/file.pdf' => 'report.pdf']
);
| 屬性/方法 | 說明 | 常用值 |
|---|---|---|
CharSet | 郵件編碼 | UTF-8(預設 ISO-8859-1,中文必改) |
SMTPSecure | 加密方式 | ssl (465) / tls (587) |
SMTPDebug | 除錯等級 | 0關閉, 1錯誤/訊息, 2完整對話, 3含連線資訊, 4低層 |
Timeout | SMTP 連線逾時(秒) | 預設 300,建議 10-30 |
DKIM_* | DKIM 簽名 | 需私鑰檔案、域名、選擇器 |
addCustomHeader() | 自定義 Header | $mail->addCustomHeader('X-Priority: 1') |
Password。telnet smtp.gmail.com 465。CharSet = 'UTF-8'、檔案儲存為 UTF-8 無 BOM、HTML meta 標籤一致。$mail->SMTPOptions = ['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]];(生產環境嚴禁)。$mail->addEmbeddedImage('/path/to/logo.png', 'logo_id', 'logo.png');
$mail->Body = '
歡迎使用我們的服務!';
PHPMailer 以「小巧、標準、可擴展」著稱。掌握其核心 API 後,配合隊列系統(Redis/RabbitMQ/Laravel Queue)即可構建高可用、可觀測的郵件發送服務。記住:永遠不要在同步 HTTP 請求中直接發送郵件,請務必異步化。