2

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?

emilal
  • 132
  • 2
  • 14

2 Answers2

10

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.

emilal
  • 132
  • 2
  • 14
  • "See this issue" links to the following GitHub-issue: https://github.com/sendgrid/sendgrid-nodejs/issues/676 – emilal Aug 17 '18 at 08:29
  • Ok Thanks i have one another problem when i am using "subject" in my msg array it doesn't write subject in email – bharat bhushan Aug 17 '18 at 10:52
  • Are you still using the templates? I am no expert here, but a solution could be having a {{subject}} variable in the subject field in the template, and then substitute it with the dynamic template data-field. – emilal Aug 18 '18 at 12:53
-1

Also you can do this:

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;
}
Oscar Corona
  • 567
  • 4
  • 5