在Ubuntu系统下配置PHP的SMTP邮件发送,可以通过以下步骤完成:
首先,确保你的系统上已经安装了PHP和相关的邮件发送扩展。你可以使用以下命令来安装:
sudo apt update
sudo apt install php php-cli php-mysql php-curl php-xml php-gd php-mbstring
PHPMailer是一个流行的PHP邮件发送库,可以帮助你更方便地发送SMTP邮件。你可以使用Composer来安装它:
sudo apt install composer
cd /var/www/html
composer require phpmailer/phpmailer
在你的Web服务器根目录(例如/var/www/html
)下创建一个新的PHP文件,例如send_email.php
,并添加以下代码:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->AuthType = 'XOAUTH2'; // Authentication type
$mail->Port = 587; // TCP port to connect to; use 465 for `SMTPS`
$mail->SMTPSecure = 'tls'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
// Sender and recipient
$mail->setFrom('from@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 <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服务器信息:
smtp.example.com
: 你的SMTP服务器地址from@example.com
: 发件人邮箱地址recipient@example.com
: 收件人邮箱地址在浏览器中访问http://your_server_ip/send_email.php
,如果一切配置正确,你应该会看到“Message has been sent”的消息,并且收件人应该会收到一封邮件。
如果你使用的是Nginx或Apache作为Web服务器,确保你的PHP文件可以通过Web服务器访问。对于Nginx,你可能需要添加一个location块来处理PHP请求:
server {
listen 80;
server_name your_server_ip;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
}
location ~ /\.ht {
deny all;
}
}
对于Apache,确保你的.htaccess
文件或虚拟主机配置允许PHP文件执行:
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
确保你的防火墙允许HTTP(端口80)和HTTPS(端口443)流量:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
完成以上步骤后,你应该能够在Ubuntu系统下成功配置PHP的SMTP邮件发送功能。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Ubuntu syslog在集群环境中的应用