问题
Following the USE CASE on SendGrids github does manage to send me the e-mail with the correct template, but the substitutions does apparently not work, and is left blank in the resulting e-mail. Server side:
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 in template:
<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>
Resulting email in my inbox:
Hello ,
I'm glad you are trying out the template feature!
I hope you are having a great day in :)
Here the variables are clearly missing. How do I substitute variables correctly?
回答1:
Since what I was using was dynamic templates from SendGrid, I cannot use the "substitutions" tag, but must instead use the "dynamic_template_data" tag, see this issue. When changing the msg-object to
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',
},
};
it works. This is not documented in the SendGrid-documentation as far as I can see.
来源:https://stackoverflow.com/questions/51650080/variable-substitution-in-sendgrid-templates-with-nodejs-does-not-work