部署 LNMP (Linux+Nginx+MySQL+PHP) 後,mail() 函式常因缺少 MTA (Mail Transfer Agent) 而失效。本文實測兩種方案:**Sendmail 簡單但極慢**、**Postfix 高效穩定**,並揭露修改 /etc/hosts 加速寄信的關鍵技巧。

yum install sendmail systemctl start sendmail systemctl enable sendmail
systemctl restart php-fpm
vi /usr/local/php/etc/php.ini # 找到 sendmail_path,修改為: sendmail_path = /usr/sbin/sendmail -t -i
systemctl restart php-fpm
<?php
$to = 'your@email.com';
$subject = 'Test from LNMP';
$message = 'Hello, this is a test mail!';
mail($to, $subject, $message) ? print('Sent') : print('Failed');
?>
訪問測試頁,信件多半進入垃圾桶,**但耗時極長(30-60 秒)**,嚴重影響使用者體驗。
# 原始 127.0.0.1 localhost.localdomain localhost # 修改為(將主機名加入 127.0.0.1) 127.0.0.1 localhost.localdomain localhost your-hostname
查詢主機名:hostname。修改後 systemctl restart sendmail,寄信速度可大幅提升(實測從 40 秒降至 3 秒內)。
yum remove sendmail
yum install postfix alternatives --set mta /usr/sbin/sendmail.postfix alternatives --display mta # 驗證已切換
/etc/postfix/main.cfvi /etc/postfix/main.cf # 取消註解並修改下列項目: myhostname = mail.yourdomain.com mydomain = yourdomain.com myorigin = $mydomain inet_interfaces = all mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain mynetworks = 192.168.100.10/28, 127.0.0.0/8 relay_domains = home_mailbox = Maildir/
systemctl start postfix systemctl enable postfix
sendmail_path = /usr/sbin/sendmail -t -i # Postfix 提供相容介面 systemctl restart php-fpm
| 指標 | Sendmail | Postfix |
|---|---|---|
| 部署複雜度 | 低 | 中 |
| 寄信延遲 | 30-60 秒(未優化 hosts 時) | < 1 秒 |
| 記憶體佔用 | 較高 | 低 |
| 安全性預設 | 較鬆 | 嚴格 |
| 維運生態 | 老舊、文件雜 | 活躍、模組豐富 |
測試環境可用 Sendmail + hosts 優化湊合;**生產環境請直接上 Postfix**,配合 SPF/DKIM/DMARC 設定,才是負責任的郵件發送姿態。