萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

IIS + PHP 環境下 sendmail 郵件發送完整配置指南

問題背景

Windows IIS 環境下 PHP mail() 函數預設依賴本機 SMTP 服務,但多數伺服器未架設郵件伺服器,需透過 sendmail for Windows 轉發至外部 SMTP(Gmail、Outlook、企業郵箱等)。

步驟 1:下載與部署 sendmail

  1. 官方下載:https://glob.com.au/sendmail/
  2. 解壓至任意目錄,例如 D:\php\sendmail\
  3. 確認目錄結構包含 sendmail.exe、sendmail.ini

步驟 2:修改 php.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 一行啟用,其餘全部註解。

步驟 3:配置 sendmail.ini(核心設定)

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

步驟 4:授權系統權限(關鍵且常被忽略)

sendmail 需呼叫 cmd.exe 執行郵件投遞,必須授予 IIS 執行身分(通常為 IUSR 或應用程式集區身分)對 C:\Windows\System32\cmd.exe 的 讀取/執行 權限:

  1. 右鍵 cmd.exe → 內容 → 安全性
  2. 編輯 → 新增 IIS 使用者身分 → 勾選「讀取與執行」

缺少權限時會出現:Warning: mail(): Could not execute mail delivery program

步驟 5:建立測試腳本驗證

建立 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

進階建議:改用 PHPMailer / Symfony Mailer

原生 mail() + sendmail 屬舊架構,現代專案建議直接使用 PHPMailer 或 Symfony Mailer:

  • 支援 SMTP 直連、OAuth2、附件、HTML/純文字多部分
  • 無需系統層級 sendmail、cmd.exe 權限
  • 錯誤處理、除錯資訊豐富
  • Composer 安裝:composer require phpmailer/phpmailer

完成上述配置後,重啟 IIS(iisreset)即可生效。若仍無法發送,請檢查 D:\php\sendmail\error.log 以及 Windows 事件檢視器中的 Application 日誌。

copyright © 萬盛學電腦網 all rights reserved