sudo apt-get update
sudo apt-get install sendmail
sudo /etc/init.d/sendmail start
# 或 systemd 系統
sudo systemctl start sendmail
sudo systemctl enable sendmail
[mail function]
SMTP = localhost
smtp_port = 25
sendmail_from = me@example.com
; Linux 通常使用 sendmail_path,建議明確指定
sendmail_path = /usr/sbin/sendmail -t -i
修改後需重啟 PHP-FPM / Apache 生效:
sudo systemctl restart php7.4-fpm或sudo systemctl restart apache2。
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
function sendMail($to, $subject, $body, $from = 'me@example.com', $fromName = '', $isHtml = true) {
$mail = new PHPMailer(true);
try {
$mail->isSendmail(); // 使用本地 sendmail
$mail->setFrom($from, $fromName ?: $from);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->msgHTML($isHtml ? $body : nl2br($body));
$mail->AltBody = $isHtml ? strip_tags($body) : $body;
$mail->send();
return true;
} catch (Exception $e) {
error_log("Mailer Error: {$mail->ErrorInfo}");
return false;
}
}
| 現象 | 可能原因 | 解決 |
|---|---|---|
| 信件卡在隊列不發送 | sendmail 服務未啟動/配置錯誤 | 檢查 mailq、/var/log/mail.log |
| 進垃圾郵件/被退信 | 缺少 SPF/DKIM/DMARC、IP 信譽差 | 配置域名 DNS 記錄、考慮使用 SMTP 服務商 (SendGrid, Mailgun) |
| PHP mail() 返回 false | sendmail_path 錯誤、權限不足 | 確認 which sendmail、php.ini 設定、禁用函數列表 |
| 中文亂碼 | 編碼未宣告 | $mail->CharSet = 'UTF-8' |
本文提供 sendmail 安裝、php.ini 配置、PHPMailer 封裝的最小可行方案,適合開發/測試環境。生產系統強烈建議接入專業郵件服務商,確保高送達率、可觀測性與合規性。