PHP 发送邮件是 web 开发中的常见需求,而 PHPMailer 是一个功能强大的 PHP 库,用于发送电子邮件。它支持 SMTP(简单邮件传输协议)以及多种邮件认证方式,使得发送邮件变得简单且安全。下面详细介绍如何使用 PHPMailer 来发送邮件。
1. 安装 PHPMailer
首先,你需要在你的项目中安装 PHPMailer。可以通过 Composer(PHP 的依赖管理工具)来安装。如果你还没有安装 Composer,需要先安装它。
在你的项目根目录下打开命令行或终端,运行以下命令来安装 PHPMailer:
composer require phpmailer/phpmailer
2. 引入 PHPMailer 类
在你的 PHP 脚本中,引入 PHPMailer 的自动加载文件,通常位于 vendor/autoload.php
。
require 'vendor/autoload.php';
3. 创建 PHPMailer 实例并配置
然后,你需要创建一个 PHPMailer 实例,并配置 SMTP 设置。以下是一个基本的配置示例:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
// 服务器设置
$mail->SMTPDebug = 2; // 启用详细调试输出
$mail->isSMTP(); // 设置邮件使用 SMTP
$mail->Host = 'smtp.example.com'; // 指定 SMTP 服务器
$mail->SMTPAuth = true; // 启用 SMTP 认证
$mail->Username = 'your_email@example.com'; // SMTP 用户名
$mail->Password = 'your_password'; // SMTP 密码
$mail->SMTPSecure = 'tls'; // 启用 TLS 加密,`ssl` 也被接受
$mail->Port = 587; // TCP 端口号
// 收件人
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Joe User'); // 添加一个收件人
// 内容
$mail->isHTML(true); // 设置电子邮件格式为 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 服务器信息:你需要根据你的邮件服务提供商(如 Gmail, Outlook, 自定义服务器等)来配置
$mail->Host
,$mail->Username
,$mail->Password
,$mail->SMTPSecure
, 和$mail->Port
。 - 调试:
$mail->SMTPDebug = 2;
会输出详细的 SMTP 通信日志,这在调试时非常有用。但请注意,在生产环境中应关闭此选项,以避免暴露敏感信息。 - 安全性:确保使用 TLS 或 SSL 加密你的 SMTP 连接,以保护你的邮件内容不被窃取。
- HTML 和纯文本邮件:通过设置
$mail->isHTML(true);
,PHPMailer 允许你发送 HTML 格式的邮件。同时,通过$mail->AltBody
,你还可以为不支持 HTML 的邮件客户端提供纯文本版本。
通过以上步骤,你就可以使用 PHPMailer 在 PHP 中发送电子邮件了。