使用Node.js的SendGrid模板中的变量替换不起作用

emi*_*lal 1 javascript node.js sendgrid-api-v3 sendgrid-templates

在SendGrids上使用USE案例之后,github确实设法向我发送了带有正确模板的电子邮件,但是替换显然不起作用,并且在生成的电子邮件中留为空白。服务器端:

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)
Run Code Online (Sandbox Code Playgroud)

模板中的HTML:

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)
Run Code Online (Sandbox Code Playgroud)

结果在我的收件箱中的电子邮件:

你好 ,

很高兴您正在尝试使用模板功能!

希望您在:)度过愉快的一天

这里显然没有变量。如何正确替换变量?

emi*_*lal 5

由于我使用的是来自SendGrid的动态模板,因此无法使用“ substitutions”标签,而必须使用“ dynamic_template_data”标签,请参见此问题。将msg-object更改为

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',
    },
};
Run Code Online (Sandbox Code Playgroud)

有用。据我所知,这未在SendGrid文档中进行记录。