阅读量:3
在Ubuntu上配置PHP以发送SMTP邮件,您可以使用PHPMailer库
- 安装PHPMailer:
通过Composer安装PHPMailer。在终端中运行以下命令:
sudo apt-get install composer
composer require phpmailer/phpmailer
- 创建一个新的PHP文件:
在您的项目目录中创建一个新的PHP文件,例如send_email.php。
- 编写代码:
在新创建的PHP文件中,编写以下代码以使用PHPMailer发送SMTP邮件:
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 = 'smtp.example.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->AuthType = 'XOAUTH2'; // OAuth2 authentication (if supported by your server)
$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 application 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}";
}
- 更新SMTP设置:
将上述代码中的以下部分替换为您的SMTP服务器和凭据:
smtp.example.com:您的SMTP服务器地址your-email@example.com:您的电子邮件地址your-app-password:您的应用程序密码(如果您的SMTP服务器支持OAuth2)
- 运行脚本:
在终端中,导航到包含send_email.php文件的目录,并运行以下命令:
php send_email.php
如果一切正常,您应该会看到“Message has been sent”的消息。如果出现错误,请检查错误消息以获取有关问题的详细信息。
以上就是关于“Ubuntu PHP配置SMTP邮件发送方法”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm