在CentOS中配置PHP以发送SMTP邮件,通常需要使用PHPMailer库或者直接配置PHP的sendmail
功能。以下是使用PHPMailer库进行配置的步骤:
通过Composer安装: 如果你的系统已经安装了Composer,可以通过以下命令安装PHPMailer:
composer require phpmailer/phpmailer
手动下载并安装: 如果没有Composer,可以从GitHub下载PHPMailer库:
wget https://github.com/PHPMailer/PHPMailer/archive/refs/tags/v6.1.0.zip
unzip v6.1.0.zip
cd PHPMailer-6.1.0/
composer install
创建一个新的PHP文件(例如send_email.php
),并添加以下代码:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// 服务器设置
$mail->SMTPDebug = 2; // 启用详细调试输出
$mail->isSMTP(); // 使用SMTP
$mail->Host = 'smtp.example.com'; // SMTP服务器地址
$mail->SMTPAuth = true; // 启用SMTP认证
$mail->AuthType = 'XOAUTH2'; // 认证类型(根据你的SMTP服务提供商)
$mail->Port = 587; // TCP端口
$mail->SMTPSecure = 'tls'; // 启用TLS加密
// 认证信息
$mail->OAuthUserEmail = 'your_email@example.com'; // 你的邮箱地址
$mail->OAuthAppId = 'your_app_id'; // OAuth应用ID
$mail->OAuthAppKey = 'your_app_key'; // OAuth应用密钥
$mail->OAuthRefreshToken = 'your_refresh_token'; // OAuth刷新令牌
// 收件人
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Recipient Name'); // 添加收件人
// 内容
$mail->isHTML(true); // 设置邮件格式为HTML
$mail->Subject = '这里是邮件的主题';
$mail->Body = '这是一封测试邮件<br><b>这是HTML格式的邮件内容</b>';
$mail->AltBody = '这是一封测试邮件\n这是纯文本格式的邮件内容';
$mail->send();
echo '消息已发送';
} catch (Exception $e) {
echo "消息无法发送. 错误信息: {$mail->ErrorInfo}";
}
?>
如果你更喜欢使用sendmail
,可以安装并配置sendmail
:
安装sendmail:
sudo yum install sendmail sendmail-cf
配置sendmail:
编辑/etc/mail/sendmail.cf
文件,添加SMTP服务器信息:
define(`SMART_HOST', `smtp.example.com')dnl
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`ESMTP_MAILER_ARGS', `TCP $h 587')dnl
define(`confAUTH_OPTIONS', `A p')dnl
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
重启sendmail服务:
sudo systemctl restart sendmail
然后,你可以使用PHP的mail()
函数发送邮件:
<?php
$to = 'recipient@example.com';
$subject = '这里是邮件的主题';
$message = '这是一封测试邮件';
$headers = 'From: from@example.com' . "\r\n" .
'Reply-To: from@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo '消息已发送';
} else {
echo '消息无法发送';
}
?>
请根据你的实际情况调整配置。