萬盛學電腦網

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

PHP 發送郵件的多種方式:mail()、管道、PHPMailer、Symfony Mailer 完整比較

PHP 發送郵件有多種路徑,各有優劣。本文系統比較 內建 mail()、管道投遞、PHPMailer、Symfony Mailer 四大主流方案,涵蓋原理、程式碼範例、優缺點、適用場景與遷移建議。

方案一:內建 mail() 函式

<?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 的單機環境。

方案二:管道投遞 (popen + sendmail/qmail)

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

qmail 專用管道範例

<?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 不支援

方案三:PHPMailer (社群最廣泛、功能最完整)

<?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}"; }

方案四:Symfony Mailer (現代、型別安全、可測試)

<?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()管道PHPMailerSymfony Mailer
相依性無系統 MTAComposer 套件Composer 套件
SMTP 驗證❌❌✅ 完整支援✅ 完整支援
HTML/替代內文手動構建手動構建✅ 內建✅ 內建
附件/內嵌圖片手動構建手動構建✅ 易用✅ 易用
異步/排隊❌❌需自行實作✅ Messenger 整合
測試支援困難困難Mock 較難✅ InMemoryTransport
型別安全❌❌部分 (PHP 8+)✅ 完整
維護狀態核心內建系統工具活躍活躍 (Symfony 核心)
學習曲線低中中中高

選型建議

  • 舊專案維護、簡單通知:`mail()` 或 管道 (若已在用)
  • 新專案、需 SMTP、附件、HTML、測試:PHPMailer (社群最大、文件豐富)
  • Symfony/Laravel 專案、重視型別安全、測試、異步隊列:Symfony Mailer
  • 高併發、大量發送:搭配 **RabbitMQ/Redis Queue + Worker** 異步發送,使用 Mailer 介面抽象
  • 企業級、合規、高送達率:改用 **交易郵件服務** (SendGrid, Mailgun, AWS SES, Postmark) + 其 SDK

遷移指南:從 mail() 升級到 PHPMailer

<?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);
copyright © 萬盛學電腦網 all rights reserved