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



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

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

在我的代码中,我希望:

  1. 收集数据并使用HTML或其他推荐的方法撰写任意数量的行/列。
  2. 使用模板撰写消息,并使用"个性化/dynamic_template_data"或任何其他推荐的方法将 (1) 中的 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

为了能够将 HTML 插入SendGrid模板,您只需在模板中使用三个大括号而不是标准的两个大括号插入变量。 😊

在 SendGrid 模板中 - 此语法会将变量textRows解释为纯文本

{{textRows}}

在 SendGrid 模板中 - 此 ayntax 会将变量textRows解释为 HTML

{{{textRows}}}

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

/K