LNMP 架構下,PHP mail() 函數依賴系統 MTA(郵件傳輸代理)投遞郵件。預設情況下缺少可用 MTA 會導致發信失效或極慢。本文提供 Sendmail 快速上手與 Postfix 企業級部署兩套方案,並針對「發信緩慢」核心痛點給出優化方案。

yum install sendmail sendmail-cf -y
systemctl enable --now sendmail
systemctl restart php-fpm
vi /usr/local/php/etc/php.ini
# 搜尋 sendmail_path,修改為:
sendmail_path = /usr/sbin/sendmail -t -i
# 重載 PHP-FPM
systemctl reload php-fpm
# 命令行測試
echo "Test body" | mail -s "Test Subject" admin@example.com
# PHP 腳本測試
Postfix 在性能、安全性、佇列管理上全面優於 Sendmail,是現代 Linux 郵件系統標準。
yum install postfix -y
systemctl enable --now postfix
# 關閉 Sendmail 避免衝突
systemctl disable --now sendmail
/etc/postfix/main.cfmyhostname = mail.yourdomain.com
mydomain = yourdomain.com
myorigin = $mydomain
inet_interfaces = localhost # 僅本機提交,不對外開放 25 埠
mydestination = $myhostname, localhost.$mydomain, localhost
mynetworks = 127.0.0.0/8
relayhost = [smtp.yourprovider.com]:587 # 智能宿主轉發(推薦)
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_security_level = encrypt
echo "[smtp.yourprovider.com]:587 user:pass" > /etc/postfix/sasl_passwd
postmap /etc/postfix/sasl_passwd
chmod 600 /etc/postfix/sasl_passwd*
systemctl reload postfix
PHP mail() 調用 sendmail/postfix 投遞時阻塞,導致 PHP-FPM 進程佔用,引發 502 Bad Gateway 或頁面卡死。
| 層級 | 方案 | 效果 |
|---|---|---|
| 系統層 | echo "127.0.0.1 $(hostname)" >> /etc/hosts | 消除本機主機名 DNS 反解延遲 |
| MTA 層 | Postfix 設 relayhost 智能轉發 + smtp_tls_security_level = encrypt | 轉發給專業郵件服務商,避免直連不穩定 |
| 應用層 | PHP 使用異步佇列(如 Laravel Queue、Symfony Messenger)或專用庫 | 完全解耦 HTTP 請求與郵件發送,毫秒級響應 |
hold 模式 + 腳本異步投遞,或引入 RabbitMQ/Redis 佇列LNMP 發信問題的本質是「同步阻塞投遞」與「缺乏專業投遞通道」。Sendmail 可作為快速驗證手段,生產環境強烈建議:Postfix 智能轉發 + 專業郵件服務商 API + 應用層異步佇列 三位一體架構,徹底解決發信慢、到達率低、維護難三大痛點。
Linux 取得指令幫助的六大管道:內建、man、info、文件、原始碼、搜尋引擎
Linux 編譯報錯 "/usr/bin/ld: cannot find -lxxx" 根因分析與解決方案
Linux 用戶登出自動重設 hosts.allow/deny 限制 IP 登入 Shell 腳本實作
Ubuntu 筆電 Bumblebee 3.0 "Tumbleweed" 散熱優化:PPA 來源更新、ironhide 移除、bbswitch 切顯卡完整實戰
Ubuntu 圖形介面建立使用者帳號:系統設定 → 使用者帳號 → 解鎖 → 新增標準/管理員帳號