在 CentOS 上配置 PHP 以發送郵件,通常使用的是 sendmail
、postfix
或 exim
等郵件傳輸代理(MTA)。以下是使用 sendmail
和 postfix
的基本步驟:
安裝 Sendmail
sudo yum install sendmail sendmail-cf mailx
配置 Sendmail
編輯 /etc/mail/sendmail.cf
文件,確保以下行沒有被注釋掉:
O DaemonPortOptions=Port=submission, Name=SMTP
然后重啟 Sendmail 服務:
sudo systemctl restart sendmail
配置 PHP
編輯你的 PHP 腳本或 php.ini
文件,設置郵件發送函數的相關參數:
ini_set('SMTP', 'localhost');
ini_set('smtp_port', '25');
ini_set('sendmail_from', 'your-email@example.com');
或者在 php.ini
文件中添加:
[mail function]
SMTP = localhost
smtp_port = 25
sendmail_from = your-email@example.com
測試郵件發送
創建一個簡單的 PHP 腳本來測試郵件發送:
<?php
$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'This is a test email sent from PHP.';
$headers = 'From: your-email@example.com' . "\r\n" .
'Reply-To: your-email@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo 'Email sent successfully.';
} else {
echo 'Email sending failed.';
}
?>
安裝 Postfix
sudo yum install postfix
配置 Postfix
編輯 /etc/postfix/main.cf
文件,進行基本配置:
myhostname = your-hostname.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, $mydomain
relayhost =
inet_protocols = ipv4
mynetworks = 127.0.0.0/8 [::1]/128
home_mailbox = Maildir/
然后重啟 Postfix 服務:
sudo systemctl restart postfix
配置 PHP
編輯你的 PHP 腳本或 php.ini
文件,設置郵件發送函數的相關參數:
ini_set('SMTP', 'localhost');
ini_set('smtp_port', '25');
ini_set('sendmail_from', 'your-email@example.com');
或者在 php.ini
文件中添加:
[mail function]
SMTP = localhost
smtp_port = 25
sendmail_from = your-email@example.com
測試郵件發送
使用與 Sendmail 相同的測試腳本進行測試。
通過以上步驟,你應該能夠在 CentOS 上成功配置 PHP 以發送郵件。