在 CentOS 上配置 PHP 郵件發送功能,通常需要以下幾個步驟:
使用以下命令安裝 Postfix:
sudo yum install postfix
安裝 Sendmail:
sudo yum install sendmail sendmail-cf mailx
對于 Postfix,編輯 /etc/postfix/main.cf
文件,根據需要進行配置。例如:
myhostname = mail.example.com
inet_interfaces = all
inet_protocols = ipv4
myorigin = $myhostname
mydestination = $myhostname, localhost.$mydomain, $mydomain
mynetworks = 127.0.0.0/8, 192.168.0.0/16
home_mailbox = Maildir/
然后重啟 Postfix 服務:
sudo systemctl restart postfix
對于 Sendmail,編輯 /etc/mail/sendmail.cf
文件,根據需要進行配置。例如:
DSNConfigDir=/etc/mail
O DaemonPortOptions=Port=submission, Name=SMTP
然后重啟 Sendmail 服務:
sudo systemctl restart sendmail
在 PHP 腳本中,可以使用 mail()
函數發送郵件。確保在 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: sender@example.com' . "\r\n" .
'Reply-To: sender@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo 'Email sent successfully.';
} else {
echo 'Email sending failed.';
}
?>
將此腳本保存為 test_email.php
,然后在瀏覽器中訪問它。如果一切配置正確,您應該會收到一封測試郵件。
注意:在實際生產環境中,建議使用更強大的郵件發送服務(如 PHPMailer 或 SwiftMailer),并考慮使用第三方 SMTP 服務(如 SendGrid、Mailgun 或 Amazon SES)來發送郵件。這樣可以提高郵件送達率并避免被標記為垃圾郵件。