这似乎是我遗漏的一个简单参数,但我很难弄清楚它到底是什么。
这是我用“@sendgrid/mail”发送的请求:
email.js:
const sgMail = require('@sendgrid/mail');
function emailRequest() {
msg = {
to: 'test+10@gmail.com
from: 'info@owner.io',
subject: 'Receipt for Business Expenses',
template_id: 'db6d11ae-41e4-4e1a-a71b-f5368eb21c9c',
personalizations: [
{
to: 'test+10@gmail.com,
from: 'info@ownr.io,
subject: 'Receipt for Business Expenses,
template_id: 'db6d11ae-41e4-4e1a-a71b-f5368eb21c9c',
substitutions: {
':firstname': 'Bobba',
':ordernumber': 'WHAAA',
':orderdate': 'today',
':ordertime': 'NOW!',
},
custom_args: {
':firstname': 'Bobba',
':ordernumber': 'WHAAA',
':orderdate': 'today',
':ordertime': 'NOW!',
},
},
],
sub: {
':firstname': 'Bobba',
':ordernumber': 'WHAAA',
':orderdate': 'today',
':ordertime': 'NOW!',
},
substitutions: {
':firstname': 'Bobba',
':ordernumber': 'WHAAA',
':orderdate': 'today',
':ordertime': 'NOW!',
},
};
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
return sgMail
.send(msg)
.then(response => {
return response;
})
.catch(err => {
throw err;
});
}
电子邮件已发送,但我仍然收到未替换的模板:
sendgrid-nodejs mail.js 的源代码似乎说只要有“替换”,它就会用这些替换初始化邮件类,但它不起作用:
https://github.com/sendgrid/sendgrid-nodejs/blob/master/packages/helpers/classes/mail.js
https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
如何正确地将变量替换到模板中?我是否使用了错误的包?
最佳答案
经过更多挖掘,我在他们的 github 的问题部分找到了答案。我缺少'substitutionWrappers'。为了让它工作,我所要做的就是在消息中添加“substitutionWrappers”和“substitutions”:
const msg = {
to: 'test@email.com'
from: 'info@gmail.io',
subject: 'Receipt for Business Expenses',
template_id: 'da6db3ae-41e4-4e1a-a71b-f5368ab41c9c',
substitutionWrappers: [':', ''],
substitutions: {
firstname: 'Bobba',
ordernumber: 'WHAAA',
orderdate: 'today',
ordertime: 'NOW!',
},
};
关于javascript - 如何替换 Sendgrid 模板变量? (在 Node js中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47112241/