在Ubuntu上配置PHP邮件服务,通常需要以下几个步骤:
安装PHP邮件发送库:
在Ubuntu上,你可以使用apt
包管理器来安装PHP的邮件发送库。对于大多数情况,推荐使用PHPMailer
库。要安装它,请运行以下命令:
sudo apt-get update
sudo apt-get install php-mailer
配置PHPMailer:
在你的项目中创建一个新的PHP文件,例如send_email.php
,然后使用以下代码配置PHPMailer:
<?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'; // OAuth2 authentication type
$mail->Port = 587; // TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->OAuthUserEmail = 'your-email@example.com'; // Your email address
$mail->OAuthPassword = 'your-app-password'; // Your OAuth2 password
// Recipients
$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.example.com
、your-email@example.com
和your-app-password
替换为你的SMTP服务器信息。
运行PHP脚本:
在终端中,导航到包含send_email.php
文件的目录,然后运行以下命令:
php send_email.php
如果一切配置正确,你应该会看到“Message has been sent”的输出。同时,收件人应该会收到一封电子邮件。
注意:在实际部署中,建议使用环境变量或其他安全方法来存储敏感信息,如SMTP凭据。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: ubuntu如何进行全盘备份