在 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)来发送邮件。这样可以提高邮件送达率并避免被标记为垃圾邮件。