node.js 发送网格实现

node.js sendgrid implementation

我已按照 SendGrid 文档创建动态交易电子邮件。 但不知何故我无法分配变量。他们总是 returns 空着。

const sgMail = require("@sendgrid/mail")
const SENDGRID_API_KEY = "deleted for safety, no worries i fill the right value here"
sgMail.setSubstitutionWrappers("{{", "}}")
sgMail.setApiKey(SENDGRID_API_KEY)

const msg = {
    to: "deleted for safety, no worries i fill the right value here",
    from: "deleted for safety, no worries i fill the right value here",
    subject: "Hello world",
    text: "Hello plain world!",
    html: "<p>Hello HTML world!</p>",
    templateId: "deleted for safety, no worries i fill the right value here",
    substitutions: {
        name: "Some One",
        city: "Denver",
    },
};
sgMail.send(msg); 

模板:

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

结果:

Hello,

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

I hope you are having a great day in :)

Api 键是正确的,结果是我收到的邮件。你们能告诉我我错过了什么吗?

安装最新版本的@sendgrid/mail 包并按照说明进行操作 在官方文档上关注 link Transactional Templates Use Case

问题是现在您必须使用 dynamic_template_data 而不是替换。您也可以删除此行

sgMail.setSubstitutionWrappers("{{", "}}")

因为从 v3 API 开始,不需要指定替代包装器,因为它会假定您使用的是车把。

这是一个应该有效的示例:

 const sgMail = require('@sendgrid/mail');
   sgMail.setApiKey(process.env.SENDGRID_API_KEY);
   const msg = {
     to: 'recipient@example.org',
     from: 'sender@example.org',
     templateId: 'd-f43daeeaef504760851f727007e0b5d0',
     dynamic_template_data: {
     subject: 'Testing Templates',
        name: 'Some One',
        city: 'Denver',
      },
   };

sgMail.send(msg);