在 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 以发送邮件。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>