在CentOS上配置PHP以通过SMTP发送邮件,您需要完成以下步骤:
-
安装并配置Postfix作为本地邮件传输代理(MTA):
a. 安装Postfix:
sudo yum install postfixb. 配置Postfix:
sudo vi /etc/postfix/main.cf在文件中添加以下内容:
myhostname = mail.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 home_mailbox = Maildir/ smtpd_sasl_auth_enable = yes smtpd_sasl_security_options = noanonymous smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination smtpd_relay_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination smtpd_tls_security_level = encrypt smtpd_tls_cert_file = /etc/pki/tls/certs/smtpd.crt smtpd_tls_key_file = /etc/pki/tls/private/smtpd.key smtpd_use_tls = yes smtp_tls_note_starttls_offer = yes smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache smtp_tls_session_cache_database = btree:${data_directory}/smtp_scachec. 替换
mail.example.com和example.com为您的实际域名。d. 重启Postfix服务:
sudo systemctl restart postfix -
安装并配置PHPMailer:
a. 使用Composer安装PHPMailer:
composer require phpmailer/phpmailerb. 创建一个新的PHP文件(例如
send_email.php),并添加以下代码:<?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; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = 'mail.example.com'; // Set the SMTP server to send through $mail->SMTPAuth = true; // Enable SMTP authentication $mail->AuthType = SMTP::AUTH_LOGIN; // Use SMTP AUTH LOGIN $mail->Port = 587; // TCP port to connect to; use 587 if you have set `SMTP_TLS` above $mail->SMTPSecure = SMTP::ENCRYPTION_STARTTLS; // Enable implicit TLS encryption $mail->Username = 'your_email@example.com'; // SMTP username $mail->Password = 'your_password'; // SMTP password // Recipients $mail->setFrom('your_email@example.com', 'Mailer'); $mail->addAddress('recipient@example.com', 'Recipient Name'); // Add a recipient // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body in bold!'; $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}"; }c. 替换
your_email@example.com、your_password和recipient@example.com为您的实际信息。 -
运行PHP脚本发送邮件:
php send_email.php
如果一切配置正确,您应该能够通过SMTP发送邮件。