应使用 composer 安装 phpmailer:composer require phpmailer/phpmailer,自动加载无需手动拷贝或修改命名空间;配置统一放在 application/extra/mail.php,确保 openssl 和 sockets 扩展已启用,并清理 opcache。

直接用 composer require phpmailer/phpmailer,别手动拷文件、改命名空间、补 namespace——那些是 TP5.0 早期没规范时的野路子,现在不仅多余,还容易出错。
用 Composer 安装并自动加载
TP5.0 支持 PSR-4 自动加载,PHPMailer 官方包已完全兼容。执行以下命令即可:
composer require phpmailer/phpmailer
安装后无需任何手动移动文件或修改源码。类会自动注册进 autoload,use PHPMailer\PHPMailer\PHPMailer; 就能直接用。
- 别再把
class.phpmailer.php放到extend/下再改名、加命名空间——TP5.0 的extend/是为非 Composer 包准备的,官方包走 Composer 更稳 - 如果项目已启用 opcache,安装后记得清下 opcache(
opcache_reset()或重启 PHP-FPM),否则可能报 “Class not found” - 确认
php_openssl.dll和sockets扩展已开启(php -m | grep -i openssl可验证)
配置项统一放 application/extra/mail.php
避免散落在 config.php 或环境变量里,也别硬编码在控制器中。新建该文件,内容如下:
<?php return [
'host' => 'smtp.163.com',
'port' => 465,
'encryption' => 'ssl',
'username' => 'yourname@163.com',
'password' => 'your_app_password', // 注意:不是邮箱登录密码,是 SMTP 授权码
'from' => 'yourname@163.com',
'from_name' => '网站名称',
];
-
encryption值必须是'ssl'或'tls',不能写'SSL'或ssl(小写无引号会解析为常量,报未定义) - 163 邮箱必须用
465端口 +ssl;QQ 邮箱推荐587+tls,用465有时会超时 -
password字段填的是「客户端授权码」,不是邮箱登录密码。网易/腾讯后台开启 SMTP 后才会生成,且仅显示一次
封装一个可复用的 MailService 类
不建议在控制器里 new PHPMailer 写一堆 setXXX——难维护、难测、易漏配置。推荐建 app/service/MailService.php:
<?php namespace app\service;
use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Config;
class MailService
{
protected $mail;
public function __construct()
{
$this->mail = new PHPMailer(true);
$this->mail->isSMTP();
$this->mail->CharSet = 'UTF-8';
$this->mail->SMTPDebug = 0; // 生产环境必须关掉
$this->mail->Host = Config::get('mail.host');
$this->mail->Port = Config::get('mail.port');
$this->mail->SMTPAuth = true;
$this->mail->SMTPSecure = Config::get('mail.encryption');
$this->mail->Username = Config::get('mail.username');
$this->mail->Password = Config::get('mail.password');
$this->mail->setFrom(Config::get('mail.from'), Config::get('mail.from_name'));
}
public function send($to, $subject, $htmlContent)
{
$this->mail->addAddress($to);
$this->mail->Subject = $subject;
$this->mail->msgHTML($htmlContent);
$this->mail->isHTML(true);
try {
return $this->mail->send();
} catch (\Exception $e) {
return $e->getMessage();
}
}
}
- 构造函数里就完成基础配置,避免每次发送都重复 set;
new MailService()后直接->send()即可 - 务必用
msgHTML()而非直接赋值Body,它会自动处理内联样式、图片 base64 编码等细节 - 捕获
\Exception(注意带反斜杠),TP5.0 默认异常处理不会透出 PHPMailer 的具体错误,不 catch 就只能看到白屏或 500
调用时别漏掉中文路径和附件编码问题
附件路径含中文、或邮件主题/正文有中文但没设编码,是 TP5.0 下最常导致“发出去但收不到”或“乱码”的两个点:
- 附件路径必须是 UTF-8 编码的英文路径,例如
/tmp/20260917_report.pdf;/tmp/报告20260917.pdf在部分 Linux 环境下会静默失败 - 即使配置了
CharSet = 'UTF-8',也要确保传入msgHTML()的$htmlContent本身是 UTF-8 编码(编辑器保存格式、数据库字段 collation 都要一致) - 调试阶段可临时打开
SMTPDebug = 2,看日志里有没有SMTP ERROR: MAIL FROM command failed或Could not connect to SMTP host—— 这类提示比 “Failed to send email” 有用得多
真正卡住的往往不是“怎么装”,而是授权码填错、端口与加密方式不匹配、或者附件路径带中文却没意识到——这些点不写死在文档里,一跑就跪。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











