在 Ubuntu 下安装 PHPMailer,您可以通过 Composer 进行安装。Composer 是一个 PHP 依赖管理工具,可以帮助您轻松地管理项目所需的库。请按照以下步骤操作:
首先,确保您已经安装了 PHP 和 Composer。如果尚未安装,请运行以下命令来安装它们:
安装 PHP:
sudo apt update
sudo apt install php php-cli php-common php-json php-pdo php-mysql php-zip php-gd php-mbstring php-curl
安装 Composer:
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
然后,导航到您的 PHP 项目目录。如果您还没有创建项目目录,请使用以下命令创建一个:
mkdir my_project
cd my_project
在项目目录中,运行以下命令以使用 Composer 安装 PHPMailer:
composer require phpmailer/phpmailer
这将在您的项目中安装 PHPMailer 及其依赖项,并在项目的 composer.json 文件中添加相应的条目。
现在,您可以在 PHP 项目中使用 PHPMailer。在您的 PHP 文件中,包含 Composer 的自动加载文件,并创建一个新的 PHPMailer 实例,如下所示:
<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// Server settings
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->AuthType = 'login';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
// Sender and recipient
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Recipient Name');
// Content
$mail->isHTML(true);
$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}";
}
请根据您的需求修改服务器设置、发件人、收件人和邮件内容。
现在,您已经成功在 Ubuntu 下安装了 PHPMailer,并可以在您的 PHP 项目中使用它。