Windows + IIS + PHP 環境中,mail() 函數預設使用本機 SMTP 服務,但 IIS 內建 SMTP 功能弱、配置繁瑣、易被判垃圾郵件。最佳實踐:使用 sendmail for Windows 偽裝成 sendmail 介面,實際透過外部 SMTP (QQ、163、Gmail 等) 發信。
D:\php\sendmail\ (路徑自訂,下文以此為例)[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25
; For Win32 only.
;sendmail_from = me@example.com
; For Unix only.
;sendmail_path = ""
; Force extra parameters
;mail.force_extra_parameters =
[mail function]
; For Win32 only.
;SMTP = localhost
;smtp_port = 25
; For Win32 only.
;sendmail_from = me@example.com
; For Unix only.
sendmail_path = "D:\php\sendmail\sendmail.exe -t"
; Force extra parameters
;mail.force_extra_parameters =
SMTP 與 smtp_port (禁用內建 SMTP)sendmail_path,指向 sendmail.exe -t (-t 從郵件標頭解析收件者)smtp_server=smtp.ym.163.com # SMTP 伺服器地址
smtp_port=25 # 或 465 (SSL), 587 (TLS)
auth_username=info@yourdomain.com # 完整郵箱帳號
auth_password=yourpassword # 郵箱密碼 (或授權碼)
force_sender=info@yourdomain.com # 強制寄件人地址
; SSL/TLS 設定
auto=1 # 自動偵測 SSL (465) 或 TLS (587)
; 或明確指定
; tls=on
; tls_starttls=on
| 郵件商 | SMTP 伺服器 | 埠號 | 加密 | 備註 |
|---|---|---|---|---|
| 163/126/Yeah.net | smtp.ym.163.com | 25/465/587 | SSL/TLS | 需開啟「SMTP 服務」獲取授權碼 |
| QQ 郵箱/企業郵箱 | smtp.qq.com / smtp.exmail.qq.com | 465/587 | SSL/TLS | 需開啟「SMTP 服務」獲取授權碼 |
| Gmail | smtp.gmail.com | 465/587 | SSL/TLS | 需開啟「兩步驟驗證」生成應用程式密碼 |
| Outlook/Hotmail | smtp.office365.com | 587 | TLS | 支援 OAuth2 現代驗證 |
iisreset /restart
# 或控制台 → 管理工具 → 服務 → 重啟 "World Wide Web Publishing Service"
<?php
$to = "test@example.com";
$subject = "IIS PHP sendmail 測試";
$message = "這是測試郵件內容。\n時間: " . date("Y-m-d H:i:s");
$headers = "From: info@yourdomain.com\r\nReply-To: info@yourdomain.com";
if (mail($to, $subject, $message, $headers)) {
echo "郵件發送成功!";
} else {
echo "郵件發送失敗,請檢查錯誤日誌。";
}
?>
| 現象 | 可能原因 | 解決方向 |
|---|---|---|
| mail() 回傳 false | sendmail.exe 路徑錯誤、權限不足 | 檢查 php.ini 路徑、給 IIS_IUSRS 讀取執行權限 |
| 郵件退信/進垃圾箱 | SPF/DKIM 未設定、IP 信譽差 | 在域名 DNS 加入 SPF 記錄、使用企業郵箱 |
| 連線逾時 | 防火牆封鎖 SMTP 埠、伺服器地址錯誤 | 開放 25/465/587 輸出、驗證 SMTP 地址 |
| 驗證失敗 | 密碼錯誤、未使用授權碼 | 確認郵箱後台開啟 SMTP、使用授權碼而非登入密碼 |
.env) 讀取auto=1 或明確 tls=on,避免明文傳輸帳密sendmail.log 定期審計替代方案:現代 PHP 專案建議使用 PHPMailer、Symfony Mailer、Laravel Mail 等成熟庫,直接支援 SMTP/TLS/OAuth2、附件、HTML 郵件、佇列等功能,無需依賴系統級 sendmail。