在 CentOS 下配置 PHP 以使用 SMTP 邮件发送功能,通常需要以下几个步骤:
sudo yum install postfix
/etc/postfix/main.cf 文件,添加以下内容:relayhost = [smtp.example.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_type = dovecot
smtp_tls_security_level = encrypt
header_size_limit = 4096000
将 smtp.example.com 替换为你的 SMTP 服务器地址。
/etc/postfix/sasl_passwd 文件,并添加以下内容:[smtp.example.com]:587 your_email@example.com:your_password
将 smtp.example.com、your_email@example.com 和 your_password 替换为你的 SMTP 服务器地址、邮箱地址和密码。
sudo postmap /etc/postfix/sasl_passwd
sudo systemctl restart postfix
composer require phpmailer/phpmailer
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->AuthType = SMTP::AUTH_LOGIN;
$mail->Port = 587;
$mail->SMTPSecure = SMTP::ENCRYPTION_STARTTLS;
// Recipients
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Recipient Name'); // Add a recipient
// Content
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
将示例中的 SMTP 服务器地址、发件人和收件人地址替换为实际值。
现在,你应该能够使用 PHPMailer 通过 SMTP 在 CentOS 上发送邮件了。