
本文介绍在使用 phpmailer 发送邮件时,如何正确加载并执行含 php 逻辑的模板文件(如 template.php),而非直接读取原始代码——核心方案是用输出缓冲(output buffering)配合 include 替代 file_get_contents。
当你使用 file_get_contents('template.php') 读取模板文件时,PHP 会将其当作纯文本处理,所有 标签及其中的逻辑(如变量输出、条件判断、循环等)都会原样暴露为 HTML 内容,导致邮件中显示 words here'; ?> 而非 'Some words here' ——这不仅破坏渲染效果,更可能泄露敏感逻辑或配置。
✅ 正确做法:使用 include + 输出缓冲(ob_start() / ob_get_clean())
include 会实际执行 PHP 文件中的代码,而输出缓冲能捕获其执行结果(即生成的 HTML 字符串),而非源码本身。修改你的 mail.php 中模板加载部分如下:
$template_file = 'PHPMailer/template.php';
if (!file_exists($template_file)) {
die("Unable to locate the template file: {$template_file}");
}
// 启动输出缓冲,包含并执行模板文件
ob_start();
include $template_file;
$mail_template = ob_get_clean(); // 获取并清空缓冲区内容
// ✅ $mail_template 现在是执行后的 HTML 字符串(如 "Some words here"),不含任何 PHP 标签⚠️ 注意事项:
立即学习“PHP免费学习笔记(深入)”;
-
不要对 $mail_template 再调用 htmlspecialchars():否则会将合法 HTML(如 ,
)转义为纯文本,破坏邮件格式。PHPMailer 的 isHTML(true) 依赖原始 HTML 结构。
- 确保模板文件中无意外输出:如 echo、print、裸露的 HTML 或空白字符(尤其文件末尾换行)均会被捕获。建议模板以
- 变量作用域安全:include 在当前作用域执行,因此 template.php 可直接访问 $smtp_mail、$settings 等已定义变量;若需严格隔离,可封装为函数或使用 extract() 控制传入数据。
- 错误处理增强:可在 ob_start() 前设置 error_reporting(0) 或使用 @include 抑制执行错误(生产环境建议配合日志记录)。
? 总结:file_get_contents 读的是“文件内容”,include + ob_* 执行的是“文件逻辑”。对于含动态 PHP 的邮件模板,后者是唯一可靠且符合预期的方式。同时,请确保模板文件不被 Web 服务器直接访问(例如置于 webroot 外,或通过 .htaccess/nginx 禁止 .php 模板的公网访问),从根源杜绝源码泄露风险。











