Windows IIS 環境下 PHP mail() 函數預設依賴本機 SMTP 服務,但多數伺服器未架設郵件伺服器,需透過 sendmail for Windows 轉發至外部 SMTP(Gmail、Outlook、企業郵箱等)。
D:\php\sendmail\sendmail.exe、sendmail.ini定位 [mail function] 區段,修改如下:
[mail function]
; SMTP = localhost ; 註解掉本機 SMTP
; smtp_port = 25
; sendmail_from = me@example.com
sendmail_path = "D:\php\sendmail\sendmail.exe -t" ; 指定 sendmail 路徑
; mail.force_extra_parameters =
關鍵點:僅保留 sendmail_path 一行啟用,其餘全部註解。
smtp_server=smtp.example.com ; SMTP 伺服器位址 (如 smtp.gmail.com)
smtp_port=587 ; 連接埠 (587 STARTTLS / 465 SSL / 25 無加密)
auth_username=your_email@example.com ; 完整信箱帳號
auth_password=your_app_password ; 應用程式專用密碼 (非登入密碼)
force_sender=your_email@example.com ; 強制寄件人位址
; SSL/TLS 設定
; auto = 465 埠自動用 SSL,其他嘗試 TLS
; 若強制 SSL:ssl=auto 或 ssl=ssl
sendmail 需呼叫 cmd.exe 執行郵件投遞,必須授予 IIS 執行身分(通常為 IUSR 或應用程式集區身分)對 C:\Windows\System32\cmd.exe 的 讀取/執行 權限:
cmd.exe → 內容 → 安全性缺少權限時會出現:Warning: mail(): Could not execute mail delivery program
建立 mail_test.php:
<?php
$to = 'test@example.com';
$subject = 'IIS PHP mail() Test';
$message = 'This is a test mail from PHP mail() via sendmail.';
$headers = 'From: your_email@example.com' . "\r\n" .
'Reply-To: your_email@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo '✅ Email sent successfully!';
} else {
echo '❌ Email sending failed!';
}
?>
瀏覽器訪問該檔案,觀察結果與收件箱(含垃圾郵件夾)。
| 現象 | 可能原因 | 解決方向 |
|---|---|---|
| 連線逾時 | 防火牆阻擋輸出 587/465/25 埠 | 開放防火牆輸出規則,或改用 API 發信 |
| 認證失敗 | 密碼錯誤/未開啟 SMTP/需應用程式密碼 | 檢查郵件商設定,啟用「低安全性應用」或產生應用程式密碼 |
| 進垃圾桶 | 缺少 SPF/DKIM/DMARC、IP 信譽差 | 配置域名 DNS 記錄,考慮使用專業交易郵件服務 |
| 中文亂碼 | 編碼未宣告 | Headers 加入 Content-Type: text/html; charset=UTF-8 |
原生 mail() + sendmail 屬舊架構,現代專案建議直接使用 PHPMailer 或 Symfony Mailer:
composer require phpmailer/phpmailer完成上述配置後,重啟 IIS(iisreset)即可生效。若仍無法發送,請檢查 D:\php\sendmail\error.log 以及 Windows 事件檢視器中的 Application 日誌。