萬盛學電腦網

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

PHP mail() 與 SMTP 完整實戰指南:從 php.ini 設定到 HTML 郵件發送

SMTP 基礎概念

SMTP (Simple Mail Transfer Protocol) 是郵件傳輸協定。PHP mail() 只是將郵件交給本機或遠端 MTA (Mail Transfer Agent),**不保證送達**,也不支援驗證、加密、附件、HTML 郵件。

php.ini 關鍵設定

指令Linux/UnixWindows
sendmail_path/usr/sbin/sendmail -t -i 或 /var/qmail/bin/sendmail -t不適用
SMTP忽略smtp.example.com 或 localhost
smtp_port忽略25 / 587 / 465
sendmail_from忽略noreply@example.com

修改後**必須重啟 Web 伺服器 / PHP-FPM** 生效。

原生 mail() 發送 HTML 郵件(含純文字備份)

<?php
function sendMail(string $to, string $subject, string $html, string $text, string $from): bool
{
    $boundary = '----' . md5(random_bytes(16));
    $headers = [
        "From: $from",
        "Reply-To: $from",
        "MIME-Version: 1.0",
        "Content-Type: multipart/alternative; boundary=\"$boundary\"",
    ];

    $message = "--$boundary\n";
    $message .= "Content-Type: text/plain; charset=UTF-8\n";
    $message .= "Content-Transfer-Encoding: base64\n\n";
    $message .= base64_encode($text) . "\n";

    $message .= "--$boundary\n";
    $message .= "Content-Type: text/html; charset=UTF-8\n";
    $message .= "Content-Transfer-Encoding: base64\n\n";
    $message .= base64_encode($html) . "\n";

    $message .= "--$boundary--";

    return mail($to, $subject, $message, implode("\r\n", $headers));
}

// 使用
sendMail(
    'user@example.com',
    '測試郵件',
    '<h1>HTML 內容</h1><p>支援中文</p>',
    '純文字備份內容',
    '系統 <noreply@example.com>'
);
?>

為什麼生產環境不建議用 mail()?

  • 無 SMTP 驗證 → 易被標記垃圾郵件
  • 無 TLS/SSL 加密 → 憑證、內容明文傳輸
  • 無退信處理、無發送隊列、無速率限制
  • Windows mail() 依賴本機 SMTP 服務,配置極其痛苦

現代解決方案:PHPMailer / Symfony Mailer

composer require phpmailer/phpmailer

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your@gmail.com';
    $mail->Password   = 'app-password'; // 應用程式密碼
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 587 port
    $mail->Port       = 587;

    $mail->setFrom('noreply@example.com', '系統通知');
    $mail->addAddress('user@example.com');
    $mail->Subject = 'PHPMailer 測試';
    $mail->Body    = '<h1>HTML 內容</h1>';
    $mail->AltBody = '純文字備份';

    $mail->send();
    echo '寄送成功';
} catch (Exception $e) {
    echo "寄送失敗: {$mail->ErrorInfo}";
}
?>

進階:非同步佇列發送

// Laravel Queue 範例
Mail::to($user)->queue(new OrderShipped($order));
// 背景 Worker 處理,HTTP 回應即時返回

郵件送達率優化清單

  • 設定 **SPF、DKIM、DMARC** DNS 記錄
  • 使用專業交易郵件服務:SendGrid、Mailgun、Amazon SES、Postmark
  • 監控退信率、投訴率、開信率
  • 提供退訂連結、實體地址(CAN-SPAM / GDPR 合規)
copyright © 萬盛學電腦網 all rights reserved