You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PrestaShop 1.6发送邮件前获取邮件内容?

解决PrestaShop模块中获取邮件模板内容为空的问题

看起来你在尝试获取PrestaShop邮件模板内容时遇到了空值问题,我来帮你排查下可能的原因并给出修复方案:

一、先修正代码里的明显错误

1. 模板名称未加引号

你的Hook调用里'template' => quotes_notify是错误的,这里应该传入字符串,要改成'template' => 'quotes_notify'。否则PHP会把quotes_notify当作常量处理,找不到的话会强制转为字符串,但这会导致钩子逻辑异常,是不规范的写法。

2. 语言ID不一致

你代码里用了$this->context->cart->id_lang,但原邮件发送函数用的是$this->context->language->id。如果当前场景没有购物车(比如后台触发的邮件),$this->context->cart会是空值,进而导致id_lang无效,找不到对应语言的模板文件。建议统一用$this->context->language->id来获取当前语言ID。

3. 缺少文件存在判断

直接用Tools::file_get_contents读取文件,如果文件不存在会返回空,你需要先判断文件是否存在,避免这种情况:

$template_html = '';
$template_txt = '';
$id_lang = $this->context->language->id;
$language = new Language($id_lang);
$iso = $language->iso_code;
$iso_template = $iso . '/quotes_notify';
$template_path = _PS_MODULE_DIR_ . $this->module->name . '/mails/';

// 先检查HTML模板文件是否存在
$html_file_path = $template_path . $iso_template . '.html';
if (file_exists($html_file_path)) {
    $template_html = Tools::file_get_contents($html_file_path);
} else {
    // 可选:如果当前语言模板不存在,回退到默认语言模板
    $default_lang = new Language(Configuration::get('PS_LANG_DEFAULT'));
    $default_iso_template = $default_lang->iso_code . '/quotes_notify';
    $default_html_path = $template_path . $default_iso_template . '.html';
    if (file_exists($default_html_path)) {
        $template_html = Tools::file_get_contents($default_html_path);
    } else {
        // 模板文件完全不存在的提示
        $template_html = 'Template file not found';
    }
}

// 调用钩子(注意修正了模板名称)
Hook::exec('actionEmailAddBeforeContent', [
    'template' => 'quotes_notify',
    'template_html' => &$template_html,
    'template_txt' => &$template_txt,
    'id_lang' => $id_lang
], null, true);

print_r($template_html);
die();

二、更可靠的方式:使用PrestaShop官方方法获取模板

PrestaShop自带Mail::getTemplateContent方法,可以帮你处理模板读取、语言回退等逻辑,比自己写更稳妥。你可以这样用:

$id_lang = $this->context->language->id;
$template_name = 'quotes_notify';
$template_path = _PS_MODULE_DIR_ . $this->module->name . '/mails/';

// 使用官方方法获取模板内容
list($template_html, $template_txt) = Mail::getTemplateContent(
    $template_name,
    $id_lang,
    $template_path
);

// 调用钩子
Hook::exec('actionEmailAddBeforeContent', [
    'template' => $template_name,
    'template_html' => &$template_html,
    'template_txt' => &$template_txt,
    'id_lang' => $id_lang
], null, true);

print_r($template_html);
die();

三、额外检查点

  • 确认你的模块邮件目录结构正确:比如modules/[你的模块名]/mails/en/quotes_notify.html(en对应语言ISO码)确实存在,并且文件权限正确(PHP能读取)。
  • 如果你是在后台触发的邮件,确保当前上下文的语言是正确的,避免读取到错误语言的模板。

内容的提问来源于stack exchange,提问作者Ahmed guesmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:16:44