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

EmailJS无法填充邮件模板全部变量字段的技术求助

问题描述

首次使用EmailJS自定义邮件模板后,邮件可正常接收,但仅datum字段能正确填充,其余指定变量字段未填充。控制台显示所有字段均已赋值,调用emailjs.sendForm时传入了对应变量,且无报错信息。

相关代码

sendEmail(e) {
  try {
    console.log(this.klantNaam, this.klantEmail, this.klantAdres, this.klantDatum, this.klantVraag); 
    // 控制台中所有字段均已赋值
    
    emailjs.sendForm('service_name', 'template_id', e.target,
    'public_key', {
      from_name: this.klantNaam,
      reply_to: this.klantEmail,
      adres: this.klantAdres,
      datum: this.klantDatum, // 仅此字段能正确填充
      message: this.klantVraag,
    })
  } catch(error) {
      console.log({error}) // 控制台无报错信息
  } 
}

邮件模板HTML代码

<p><strong>Afzender:</strong></p>
<p>{{reply_to}}</p>
<p><strong>Nieuw bericht:</strong></p>
<p>{{message}}</p>
<p><strong>Adres:</strong></p>
<p>{{adres}}</p>
<p><strong>Wanneer komt het uit?</strong></p>
<p>{{datum}}</p>
<p>&nbsp;</p>
<p><em>Automatisch gegenereerd bericht</em></p>
<p>&nbsp;</p>

问题原因

  1. sendForm参数顺序错误:你传入的模板参数对象位置不符合方法要求,emailjs.sendForm无法识别该位置的参数,导致除datum外的变量无法传递。
  2. datum正常填充的特殊情况:你的表单元素(e.target)中恰好存在name="datum"的字段,sendForm会自动从表单提取该字段的值,所以这个变量能正常填充;而其他变量对应的表单字段要么不存在,要么name属性和模板变量名不匹配,无法被自动提取。

解决方法

方法一:修正sendForm参数结构

将公钥和模板参数放入配置对象中,确保参数被正确识别:

sendEmail(e) {
  try {
    console.log(this.klantNaam, this.klantEmail, this.klantAdres, this.klantDatum, this.klantVraag); 
    
    emailjs.sendForm('service_name', 'template_id', e.target, {
      publicKey: 'public_key',
      templateParams: {
        from_name: this.klantNaam,
        reply_to: this.klantEmail,
        adres: this.klantAdres,
        datum: this.klantDatum,
        message: this.klantVraag,
      }
    })
  } catch(error) {
      console.log({error})
  } 
}

方法二:让表单字段name与模板变量匹配

如果想依赖sendForm自动提取表单数据的特性,修改表单中输入框的name属性,使其与模板变量完全一致:

<!-- 示例表单字段 -->
<input type="text" name="reply_to" value="" />
<input type="text" name="message" value="" />
<input type="text" name="adres" value="" />
<input type="text" name="datum" value="" />

之后简化代码,无需手动传入模板参数:

sendEmail(e) {
  try {
    emailjs.sendForm('service_name', 'template_id', e.target, 'public_key')
  } catch(error) {
      console.log({error})
  } 
}

方法三:改用send方法(更灵活)

如果数据并非来自表单,或者不想依赖表单字段,直接使用emailjs.send手动传递所有参数:

sendEmail(e) {
  try {
    console.log(this.klantNaam, this.klantEmail, this.klantAdres, this.klantDatum, this.klantVraag); 
    
    emailjs.send('service_name', 'template_id', {
      from_name: this.klantNaam,
      reply_to: this.klantEmail,
      adres: this.klantAdres,
      datum: this.klantDatum,
      message: this.klantVraag,
    }, 'public_key')
  } catch(error) {
      console.log({error})
  } 
}

内容的提问来源于stack exchange,提问作者G Buis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:24:54