最简安装方式是运行 composer require phpmailer/phpmailer,Composer 会自动安装最新稳定版 v6.x 并配置 PSR-4 自动加载;v5 已废弃且不兼容 PHP 8+,混用命名空间会导致 Class 'PHPMailer' not found。

直接运行 composer require phpmailer/phpmailer 就行
这是最简方式,Composer 会自动拉取最新稳定版(目前是 v6.x),并写入 composer.json 和 vendor/ 目录。不需要手动下载 ZIP 或改 autoload —— Composer 原生支持 PSR-4 自动加载,只要项目已初始化(有 composer.json),执行命令后就能直接 use PHPMailer\PHPMailer\PHPMailer;。
为什么不能用 composer require phpmailer/phpmailer:5.2.27?
v5 版本已废弃,官方明确停止维护,且与 PHP 8+ 兼容性差。常见报错包括:Deprecated: Methods with the same name as their class will not be constructors(PHP 7.2+ 报 strict warning)、Call to undefined method PHPMailer::isSMTP()(因命名空间和类结构变更)。v6 要求显式启用命名空间,v5 是全局类名,混用会导致 Class 'PHPMailer' not found。
- v6 默认使用
PHPMailer\PHPMailer\PHPMailer完整命名空间 - v5 的
require 'class.phpmailer.php'方式在 v6 中完全失效 - 若遗留老项目必须兼容 v5,请确认 PHP ≤ 7.1,并加
"phpmailer/phpmailer": "5.2.27"到composer.json的require段,再composer update
use 语句和实例化怎么写才不报错?
常见错误是漏掉子命名空间或写错大小写。v6 的核心类路径是固定的,必须严格匹配:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true); // true 表示开启异常抛出
try {
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@gmail.com';
$mail->Password = 'app-password'; // 注意:Gmail 需用应用专用密码
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->setFrom('your@gmail.com', 'Sender Name');
$mail->addAddress('to@example.com');
$mail->isHTML(true);
$mail->Subject = 'Test';
$mail->Body = 'Hello
';
$mail->send();
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
关键点:
立即学习“PHP免费学习笔记(深入)”;
- 必须
use三个类:主类、SMTP(仅当调用isSMTP()时需,但建议显式引入)、Exception(捕获异常必需) -
new PHPMailer(true)的true很重要——不加则异常静默失败,debug 时完全看不到报错 - Gmail 等现代 SMTP 服务强制要求应用专用密码(App Password),不是账户登录密码
本地开发发不了邮件?先检查这三件事
90% 的“发送失败”问题跟配置无关,而是环境限制:
- 本地 PHP CLI 环境默认禁用
fsockopen和stream_socket_client—— 这两个函数被 PHPMailer 用于建立 SMTP 连接,需在php.ini中取消注释extension=openssl并确保未禁用上述函数 - Windows 下 WAMP/XAMPP 默认关闭 OpenSSL 扩展,Linux/Mac 用户常忽略
cafile路径,导致 SSL 握手失败(报错类似SMTP Error: Could not connect to SMTP host) -
防火墙或杀毒软件拦截 465/587 端口(尤其公司内网),可临时换用
SMTPDebug = 2查看连接阶段卡在哪一步
调试时加这两行能快速定位链路断点:
$mail->SMTPDebug = 2; // 显示 SMTP 通信过程
$mail->Debugoutput = function($str) { echo $str . "
"; };
真正麻烦的从来不是代码写法,而是 OpenSSL 是否就绪、端口是否放行、以及你填的到底是邮箱密码还是应用专用密码。











