Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

IIS + PHP 環境下 sendmail 郵件發送完整配置教學 (支援 QQ/163/Gmail SMTP)

編輯:關於伺服器

場景與痛點

Windows + IIS + PHP 環境中,mail() 函數預設使用本機 SMTP 服務,但 IIS 內建 SMTP 功能弱、配置繁瑣、易被判垃圾郵件。最佳實踐:使用 sendmail for Windows 偽裝成 sendmail 介面,實際透過外部 SMTP (QQ、163、Gmail 等) 發信。

工具準備

  • 下載:sendmail.zip (官方網站)
  • 解壓至:D:\php\sendmail\ (路徑自訂,下文以此為例)

第一階段:修改 php.ini

原始設定 (預設使用本機 SMTP)

[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 =

修改後 (啟用 sendmail)

[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 從郵件標頭解析收件者)
  • 路徑請根據實際解壓位置調整

第二階段:配置 sendmail.ini

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 設定參考

郵件商SMTP 伺服器埠號加密備註
163/126/Yeah.netsmtp.ym.163.com25/465/587SSL/TLS需開啟「SMTP 服務」獲取授權碼
QQ 郵箱/企業郵箱smtp.qq.com / smtp.exmail.qq.com465/587SSL/TLS需開啟「SMTP 服務」獲取授權碼
Gmailsmtp.gmail.com465/587SSL/TLS需開啟「兩步驟驗證」生成應用程式密碼
Outlook/Hotmailsmtp.office365.com587TLS支援 OAuth2 現代驗證

第三階段:重啟 IIS 驗證

iisreset /restart
# 或控制台 → 管理工具 → 服務 → 重啟 "World Wide Web Publishing Service"

測試腳本 (test_mail.php)

<?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() 回傳 falsesendmail.exe 路徑錯誤、權限不足檢查 php.ini 路徑、給 IIS_IUSRS 讀取執行權限
郵件退信/進垃圾箱SPF/DKIM 未設定、IP 信譽差在域名 DNS 加入 SPF 記錄、使用企業郵箱
連線逾時防火牆封鎖 SMTP 埠、伺服器地址錯誤開放 25/465/587 輸出、驗證 SMTP 地址
驗證失敗密碼錯誤、未使用授權碼確認郵箱後台開啟 SMTP、使用授權碼而非登入密碼

進階安全建議

  • 不要在程式碼寫死密碼:使用環境變數或設定檔 (如 .env) 讀取
  • 限制發信頻率:應用層加入節流,防止被盜用刷信
  • 啟用 TLS 加密:auto=1 或明確 tls=on,避免明文傳輸帳密
  • 監控發信日誌:sendmail 產生的 sendmail.log 定期審計

替代方案:現代 PHP 專案建議使用 PHPMailer、Symfony Mailer、Laravel Mail 等成熟庫,直接支援 SMTP/TLS/OAuth2、附件、HTML 郵件、佇列等功能,無需依賴系統級 sendmail。

Copyright © Windows教程網 All Rights Reserved