如何在JavaScript中将动态数据(HTML)插入SendGrid模板

10

我希望使用SendGrid模板发送电子邮件。 我使用标准的v3 API和简单的axios调用。

我希望使用模板发送一封电子邮件。 邮件应包含多行和列。 我不知道在创建模板时会有多少行/列。 行数/列数将取决于仅在撰写电子邮件时了解的数据。

在我的代码中,我希望:

  1. 收集数据并使用HTML或其他推荐方法组合任意数量的行/列。
  2. 使用模板组成消息,并使用“personalizations/dynamic_template_data”或任何其他推荐方法将我的HTML插入模板中。
  3. 发送电子邮件。
  4. 我希望电子邮件将我的HTML行/列视为HTML。

我的代码(不起作用- HTML被视为文本):

  //Coompose HTML
  let alertHtml = ''
  noteObjArray.forEach((nototObj)=>{
    ...
    alertHtml += (myDate !== '') ? `- ${someText} ${myDate } ` : ''
    ...
    alertHtml += '<br/>'
  })

  //Send mail using SendGrid  
  const mailSender = firebaseFunctionsConfig.sendgrid.sender
  const msg = {
    personalizations: [{
      to: [{email, name}],
      dynamic_template_data: {userName:name, amount, alertHtml}
    }],
    from: {email: mailSender.email, name: mailSender.name},
    reply_to: {email: mailSender.replyemail, name: mailSender.replyname},
    template_id: 'a-000078d4b2eb666940bbg1ee66s'
    // "content": [{"type": "text/html"}] 
  }

提前感谢!/K

1个回答

35

如果想要在SendGrid模板中插入HTML,只需在模板中使用三个花括号插入变量即可,而不是标准的两个

在SendGrid模板中,这种语法会将变量textRows解释为纯文本。

{{textRows}}
在SendGrid模板中 - 这个语法将把变量textRows解释为HTML。
{{{textRows}}}

感谢Kyle Roberts在GitHub上发布解决方案!

/K


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接