我已遵循SendGrid文档来创建动态交易电子邮件。 但是由于某种原因,我无法分配变量。他们总是返回空。
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>
结果:
你好,
很高兴您正在尝试使用模板功能!
我希望您在:)过得愉快。
Api密钥正确,结果是我收到的邮件。你们能告诉我我在想什么吗?
答案 0 :(得分:1)
安装最新版本的@ sendgrid / mail软件包,然后按照 以下官方文档链接 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);