SMTP (Simple Mail Transfer Protocol) 是郵件傳輸協定。PHP mail() 只是將郵件交給本機或遠端 MTA (Mail Transfer Agent),**不保證送達**,也不支援驗證、加密、附件、HTML 郵件。
| 指令 | Linux/Unix | Windows |
|---|---|---|
| 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** 生效。
<?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 服務,配置極其痛苦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 回應即時返回