【问题标题】:Variable substitution in SendGrid templates with Nodejs does not work使用 Nodejs 的 SendGrid 模板中的变量替换不起作用
【发布时间】:2018-08-02 09:26:09
【问题描述】:

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

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:

<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>

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

你好,

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

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

这里的变量显然丢失了。 如何正确替换变量?

【问题讨论】:

    标签: javascript node.js sendgrid-api-v3 sendgrid-templates


    【解决方案1】:

    由于我使用的是来自 SendGrid 的 dynamic 模板,因此我不能使用“substitutions”标签,而必须使用“dynamic_template_data”标签,请参阅this issue。当将 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',
        },
    };
    

    它有效。据我所知,SendGrid 文档中没有记录。

    【讨论】:

    • “查看此问题”链接到以下 GitHub 问题:github.com/sendgrid/sendgrid-nodejs/issues/676
    • 好的,谢谢,当我在我的 msg 数组中使用“主题”时,它没有在电子邮件中写入主题
    • 您还在使用模板吗?我不是这里的专家,但解决方案可能是在模板的主题字段中使用 {{subject}} 变量,然后用动态模板数据字段替换它。
    【解决方案2】:

    你也可以这样做:

    import { getConfig } from '../config';    
    const msg = {
                    to: recipient,
                    from: global.gConfig['SENDGRID_EMAIL_FROM'], // or getConfig().SENDGRID_EMAIL_FROM
                    templateId: this.templateId,
                    dynamicTemplateData: this.variables,
        };
    

    getConfig.ts

    export function getConfig(): any {
        return process.env;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 2016-11-10
      • 2012-10-15
      • 1970-01-01
      相关资源
      最近更新 更多