Variable substitution in SendGrid templates with Nodejs does not work

我只是一个虾纸丫 提交于 2019-12-02 09:42:39

问题


Following the USE CASE on SendGrids github does manage to send me the e-mail with the correct template, but the substitutions does apparently not work, and is left blank in the resulting e-mail. Server side:

const sgmailer = require("@sendgrid/mail");
sgmailer.setApiKey(process.env.SENDGRID_API_KEY);
sgmailer.setSubstitutionWrappers('{{', '}}');

const msg = {
    to: '...',
    from: 'sender@example.org',
    subject: 'Hello world',
    text: 'Hello plain world!',
    html: '<p>Hello HTML world!</p>',
    templateId: '...',
    substitutions: {
        name: 'Some One',
        city: 'Denver',
    },
};
sgmailer.send(msg)

HTML in template:

<html>
<head>
    <title></title>
</head>
<body>
Hello {{name}},
<br /><br/>
I'm glad you are trying out the template feature!
<br /><br/>
<%body%>
<br /><br/>
I hope you are having a great day in {{city}} :)
<br /><br/>
</body>
</html>

Resulting email in my inbox:

Hello ,

I'm glad you are trying out the template feature!

I hope you are having a great day in :)

Here the variables are clearly missing. How do I substitute variables correctly?


回答1:


Since what I was using was dynamic templates from SendGrid, I cannot use the "substitutions" tag, but must instead use the "dynamic_template_data" tag, see this issue. When changing the msg-object to

const msg = {
    to: '...',
    from: 'sender@example.org',
    subject: 'Hello world',
    text: 'Hello plain world!',
    html: '<p>Hello HTML world!</p>',
    templateId: '...',
    dynamic_template_data: {
        name: 'Some One',
        city: 'Denver',
    },
};

it works. This is not documented in the SendGrid-documentation as far as I can see.



来源:https://stackoverflow.com/questions/51650080/variable-substitution-in-sendgrid-templates-with-nodejs-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!