PHP 發送郵件有多種路徑,各有優劣。本文系統比較 內建 mail()、管道投遞、PHPMailer、Symfony Mailer 四大主流方案,涵蓋原理、程式碼範例、優缺點、適用場景與遷移建議。
<?php
// 最簡單用法
$to = 'user@example.com';
$subject = '測試郵件';
$message = '這是純文字內容';
$headers = "From: system@example.com\r\n" .
"Reply-To: system@example.com\r\n" .
"Content-Type: text/plain; charset=UTF-8\r\n";
mail($to, $subject, $message, $headers);
| 優點 | 缺點 |
|---|---|
| 零相依、語法簡單 | 功能極簡:無 SMTP 驗證、無附件、無 HTML/替代內文 |
| 無需額外安裝 | 依賴本地 MTA (sendmail/postfix/qmail) 設定正確 |
| 效能開銷最低 | 難以除錯、無發送狀態回傳、易進垃圾箱 |
| Windows 環境需額外設定 SMTP 伺服器 |
適用:簡單通知、開發測試、已完善配置本地 MTA 的單機環境。
<?php
// 使用 sendmail 管道
$sendmail = '/usr/sbin/sendmail -t -i'; // -t 從郵件頭讀取收件者, -i 忽略單獨 . 行
$fp = popen($sendmail, 'w');
if (!$fp) die('無法開啟 sendmail 管道');
fwrite($fp, "To: user@example.com\r\n");
fwrite($fp, "From: system@example.com\r\n");
fwrite($fp, "Subject: 測試郵件\r\n");
fwrite($fp, "Content-Type: text/html; charset=UTF-8\r\n");
fwrite($fp, "\r\n");
fwrite($fp, "HTML 內容
支援豐富格式
\r\n");
fwrite($fp, "\r\n");
pclose($fp);
<?php
function sendViaQmail(string $to, string $subject, string $html, string $from = 'noreply@example.com'): bool
{
$cmd = '/var/qmail/bin/qmail-inject ' . escapeshellarg($to);
$fp = popen($cmd, 'w');
if (!$fp) return false;
fwrite($fp, "From: $from\r\n");
fwrite($fp, "Subject: $subject\r\n");
fwrite($fp, "MIME-Version: 1.0\r\n");
fwrite($fp, "Content-Type: text/html; charset=UTF-8\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $html . "\r\n");
return pclose($fp) === 0;
}
| 優點 | 缺點 |
|---|---|
| 直接控制 MTA 輸入、支援完整 MIME | 綁定特定 MTA (sendmail/qmail/postfix)、可攜性差 |
| 繞過 PHP mail() 限制、可注入自定標頭 | 需管理管道權限、錯誤處理困難、阻塞式 I/O |
| 效能優於 mail() (避免 fork 開銷) | 非標準做法、維護困難、Windows 不支援 |
<?php
// composer require phpmailer/phpmailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// SMTP 設定
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@gmail.com';
$mail->Password = 'app_password'; // 應用程式密碼
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// 發件人/收件人
$mail->setFrom('your@gmail.com', '系統名稱');
$mail->addAddress('recipient@example.com', '收件者名稱');
$mail->addReplyTo('reply@example.com', '回覆地址');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');
// 附件
$mail->addAttachment('/path/to/file.pdf', 'report.pdf');
$mail->addStringAttachment($pdfContent, 'generated.pdf');
// 內容
$mail->isHTML(true);
$mail->Subject = 'PHPMailer 測試';
$mail->Body = 'HTML 內容
支援 粗體、圖片、連結
';
$mail->AltBody = '純文字替代內容 (非 HTML 郵件客戶端)';
// 內嵌圖片
$mail->addEmbeddedImage('/path/logo.png', 'logo_id', 'logo.png');
// HTML 中使用:
$mail->send();
echo '發送成功';
} catch (Exception $e) {
echo "發送失敗: {$mail->ErrorInfo}";
}
<?php
// composer require symfony/mailer symfony/mime
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
$transport = new EsmtpTransport('smtp.example.com', 587, 'tls');
$transport->setUsername('user');
$transport->setPassword('pass');
$mailer = new Mailer($transport);
$email = (new Email())
->from(new Address('system@example.com', '系統'))
->to('user@example.com')
->subject('Symfony Mailer 測試')
->text('純文字內容')
->html('HTML 內容
支援 Twig 模板
')
->attachFromPath('/path/report.pdf', 'report.pdf')
->embed(fopen('/path/logo.png', 'r'), 'logo.png'); // 內嵌圖片 cid:logo.png
$mailer->send($email);
| 維度 | mail() | 管道 | PHPMailer | Symfony Mailer |
|---|---|---|---|---|
| 相依性 | 無 | 系統 MTA | Composer 套件 | Composer 套件 |
| SMTP 驗證 | ❌ | ❌ | ✅ 完整支援 | ✅ 完整支援 |
| HTML/替代內文 | 手動構建 | 手動構建 | ✅ 內建 | ✅ 內建 |
| 附件/內嵌圖片 | 手動構建 | 手動構建 | ✅ 易用 | ✅ 易用 |
| 異步/排隊 | ❌ | ❌ | 需自行實作 | ✅ Messenger 整合 |
| 測試支援 | 困難 | 困難 | Mock 較難 | ✅ InMemoryTransport |
| 型別安全 | ❌ | ❌ | 部分 (PHP 8+) | ✅ 完整 |
| 維護狀態 | 核心內建 | 系統工具 | 活躍 | 活躍 (Symfony 核心) |
| 學習曲線 | 低 | 中 | 中 | 中高 |
<?php
// 統一介面封裝,漸進式遷移
interface MailerInterface
{
public function send(string $to, string $subject, string $html, string $text = '', array $attachments = []): bool;
}
class PhpMailerAdapter implements MailerInterface
{
// ... 實作介面,內部使用 PHPMailer
}
class NativeMailAdapter implements MailerInterface
{
// ... 實作介面,內部使用 mail()
}
// 依賴注入容器綁定
// $container->bind(MailerInterface::class, PhpMailerAdapter::class);