萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

LNMP 環境下 PHP mail() 無法寄信?雙方案實測:Sendmail 慢、Postfix 快、優化 hosts 加速

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

LNMP 郵件發送架構圖

方案一:Sendmail —— 幾分鐘上手,但寄信需 30-60 秒

1. 安裝與啟動

yum install sendmail
systemctl start sendmail
systemctl enable sendmail

2. 重啟 PHP-FPM 載入新 MTA

systemctl restart php-fpm

3. 修改 php.ini 指定 sendmail 路徑

vi /usr/local/php/etc/php.ini
# 找到 sendmail_path,修改為:
sendmail_path = /usr/sbin/sendmail -t -i

4. 再次重啟 PHP-FPM

systemctl restart php-fpm

5. 測試寄信

<?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 秒)**,嚴重影響使用者體驗。

6. 加速關鍵:修改 /etc/hosts

# 原始
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 秒內)。

方案二:Postfix —— 生產環境首選,毫秒級寄出

1. 移除 Sendmail 避免衝突

yum remove sendmail

2. 安裝並設為預設 MTA

yum install postfix
alternatives --set mta /usr/sbin/sendmail.postfix
alternatives --display mta  # 驗證已切換

3. 核心配置 /etc/postfix/main.cf

vi /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/

4. 啟動與開機自啟

systemctl start postfix
systemctl enable postfix

5. PHP 端同樣指向 sendmail 相容介面

sendmail_path = /usr/sbin/sendmail -t -i  # Postfix 提供相容介面
systemctl restart php-fpm

方案對比總結

指標SendmailPostfix
部署複雜度低中
寄信延遲30-60 秒(未優化 hosts 時)< 1 秒
記憶體佔用較高低
安全性預設較鬆嚴格
維運生態老舊、文件雜活躍、模組豐富

結語

測試環境可用 Sendmail + hosts 優化湊合;**生產環境請直接上 Postfix**,配合 SPF/DKIM/DMARC 設定,才是負責任的郵件發送姿態。

copyright © 萬盛學電腦網 all rights reserved