PHP mail() 預設呼叫 sendmail 二進制發送郵件。CentOS/RHEL 最小安裝未預裝 sendmail,導致 mail() 靜默失敗。
yum install sendmail sendmail-cf m4 -y
# CentOS 6 service sendmail start chkconfig sendmail on # CentOS 7 / RHEL 7+ systemctl start sendmail systemctl enable sendmail
service sendmail status # 或 systemctl status sendmail
顯示 running 即正常。
# 找到 php.ini 位置 php --ini | grep "Loaded Configuration" # 通常為 /etc/php.ini 或 /usr/local/php/etc/php.ini # 編輯 php.ini vi /etc/php.ini # 找到 ;sendmail_path = 取消註解並修改為: sendmail_path = /usr/sbin/sendmail -t -i
-t 從郵件標頭解析收件者,-i 忽略單獨「.」行作為結束標記。
# PHP-FPM service php-fpm restart # 或 systemctl restart php-fpm # Apache 模組模式 service httpd restart # 或 systemctl restart httpd
php -r "mail('test@example.com', 'Test Subject', 'Test Body', 'From: sender@example.com');"
# 或寫入測試腳本 test_mail.php 透過瀏覽器/CLI 執行
| 現象 | 可能原因 | 解決 |
|---|---|---|
| 郵件進垃圾桶/被退信 | 無 SPF/DKIM/DMARC、IP 信譽差 | 設定 DNS 記錄、使用 SMTP 轉發(Postfix/Exim + relayhost) |
| sendmail 啟動慢 | 主機名稱解析失敗 | 確認 /etc/hosts 含 127.0.0.1 localhost.localdomain localhost hostname |
| PHP 仍報錯 | php.ini 未生效、路徑錯誤 | php -i | grep sendmail_path 驗證實際生效值 |
| SELinux 阻擋 | httpd_can_sendmail 關閉 | setsebool -P httpd_can_sendmail 1 |