不想依賴第三方 SMTP 服務?PHP 內建 mail() 搭配 sendmail 即可透過指定郵件伺服器發送。本文詳細說明 Windows 環境完整設定流程。
D:\sendmail\; D:\sendmail\sendmail.ini
[sendmail]
smtp_server=smtp.qq.com
smtp_port=25
; smtp_port=465 (SSL) 或 587 (TLS)
error_logfile=error.log
debug_logfile=debug.log
auth_username=your_email@qq.com
auth_password=your_auth_code ; QQ郵箱需用授權碼,非登入密碼
force_sender=your_email@qq.com
; php.ini [mail function] 區段
[mail function]
SMTP = smtp.qq.com
smtp_port = 25
sendmail_from = your_email@qq.com
sendmail_path = "D:/sendmail/sendmail.exe -t -i"
mail.add_x_header = On
⚠️ 修改 php.ini 後必須重啟 Apache/Nginx 才生效。
<?php
$to = "recipient@example.com";
$subject = "測試郵件";
$message = "這是一封測試郵件。\n換行測試。";
$headers = "From: 寄件者 \r\n";
$headers .= "Reply-To: your_email@qq.com\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "郵件已送出 (已交給郵件系統)";
} else {
echo "郵件發送失敗";
}
?>
<?php
$to = "user@example.com";
$subject = "HTML 郵件測試";
$message = "
<html>
<head><title>HTML 郵件</title></head>
<body>
<h1>歡迎註冊</h1>
<p>親愛的用戶,感謝您的註冊!</p>
<table border='1' cellpadding='5'>
<tr><th>項目</th><th>內容</th></tr>
<tr><td>帳號</td><td>user123</td></tr>
</table>
</body>
</html>
";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$headers .= "From: 系統 \r\n";
$headers .= "Cc: admin@example.com\r\n";
mail($to, $subject, $message, $headers);
?>
<?php
// Windows 下 SMTP 若行首為句號會被移除,需雙倍轉義
$message = str_replace("\n.", "\n..", $message);
?>
| 問題 | 原因與解決 |
|---|---|
| 發送失敗 | 檢查 sendmail debug.log、error.log;確認 25/465/587 埠通;防火牆/雲安全組 |
| 進垃圾箱 | 設定 SPF/DKIM/DMARC;避免敏感詞;使用可信域名 |
| 中文亂碼 | 統一 UTF-8:header charset、檔案編碼、資料庫編碼 |
| 163/GMail 退信 | 免費郵箱限制嚴格,建議用企業郵箱或專業送信服務 |
| 附件發送 | 原生 mail() 處理附件極複雜,請用 PHPMailer |
<?php
// composer require phpmailer/phpmailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.qq.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@qq.com';
$mail->Password = 'auth_code';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SSL 465
$mail->Port = 465;
$mail->setFrom('your@qq.com', '系統名稱');
$mail->addAddress('to@example.com');
$mail->Subject = '主題';
$mail->Body = 'HTML 內容';
$mail->AltBody = '純文字備用';
$mail->send();
echo "發送成功";
} catch (Exception $e) {
echo "發送失敗: {$mail->ErrorInfo}";
}
?>
PHPMailer 優勢:SMTP 認證、SSL/TLS、附件、內嵌圖片、多收件人、佇列、異步發送、完善錯誤處理、相容所有主流郵件服務商。