在Ubuntu下配置PHP以使用SMTP发送邮件,您需要按照以下步骤操作:
首先,您需要在项目中安装PHPMailer库。您可以使用Composer来安装它。在项目根目录下运行以下命令:
composer require phpmailer/phpmailer
创建一个新的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 = 'login'; // Authentication type (LOGIN, PLAIN, CRAM-MD5, DIGEST-MD5, XOAUTH2)
$mail->Port = 587; // TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable implicit TLS encryption
$mail->Username = 'your_email@example.com'; // SMTP username
$mail->Password = 'your_password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable explicit TLS encryption
// 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服务器和帐户信息:
smtp.example.com
:您的SMTP服务器地址your_email@example.com
:您的SMTP用户名your_password
:您的SMTP密码from@example.com
:发件人的电子邮件地址recipient@example.com
:收件人的电子邮件地址保存send_email.php
文件并通过命令行运行它:
php send_email.php
如果一切正常,您应该会看到“Message has been sent”的消息。如果出现错误,请检查您的SMTP设置以及防火墙和网络连接。