Sendgrid-nodejs: How to send template in "@sendgrid/mail": "^6.1.3”?

Created on 16 Sep 2017  ·  6Comments  ·  Source: sendgrid/sendgrid-nodejs

Hi! How can I use a template and replace it with substitutions and then send it? Thank you so much! I use @sendgrid/mail" "^6.1.3 ?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const sgMail = require('@sendgrid/mail');

module.exports = functions.auth.user().onCreate(event => {
    const user = event.data; // The Firebase user.

    const email = user.email; // The email of the user.
    const displayName = user.displayName; // The display name of the user.

    if (email == null || email == undefined) {
        return console.log("email == null")
    }

    const SENDGRID_API_KEY = functions.config().sendgrid.emailapikey;

    sgMail.setApiKey(SENDGRID_API_KEY);
    sgMail.setSubstitutionWrappers("%", "%");

    var msg = {
        to: email,
        from: '[email protected]',
        subject: 'Welcome to myapp!',
    };


    // Tell SendGrid which template to use, and what to substitute. You can use as many substitutions as you want.
    msg.setFilters({"templates": {"settings": {"enabled": 1, "template_id": "templatekey"}}}); // Just replace this with the ID of the template you want to use
    msg.addSubstitution('%fname%', displayName); // You don't need to have a subsitution, but if you want it, here's how you do that :)

    const sendMessagePromise = sgMail.send(msg);

    return Promise.all([sendMessagePromise]).then(() => {
        return console.log("success")
        }).catch((err) => {
            return console.log(err);
            });

    });

Most helpful comment

@milottit If you haven't figured it out already and for new comers who stumble along this ticket, I was getting the same successful result you were but no email response. How I resolved this, I used the following code.

Note below the following format in the 'dynamic_template_data' variable.

"name": 'Test'

I believe you need to send the variable you want to replace in the template as a string.

Sendgrid.setApiKey(SENDGRID_API_KEY);
const email =
{
    to: '[email protected]',
    from: SENDGRID_SENDER,
    subject: 'Test',
    template_id: 'd-128e110d98e040c6b81f4694d04e0572',
    dynamic_template_data: {
        "name": 'Test',
        "club_name": 'VTR School',
    },
};
Sendgrid.send(email)
    .then(m => {
        console.log('Mail sent');
    })
    .catch(error => {
        //Log friendly error
        console.error(error.toString());
    });

Hope this helps!

All 6 comments

Hi @alexsanderkhitev,

Here is a full example. I hope that helps!

With Best Regards,

Elmer

Hey @thinkingserious, is there any reason why my template email isn't sending?

I'm using the same exact code above and no luck. I'm on Heroku using the integrated Sendgrid app. Any help is appreciated. Also, I'm grabbing the templateId from the url. Is that correct?

Thanks for the help!

Hi @thinkingserious,

Thank you! It helped me!

With Best Regards,

Alexander

Hi @georgeportillo,

Could you please provide some example code for "grabbing the templateId from the url"? I'm not quite sure what you mean. In the end, the value of that variable should be the Template ID, similar to "13b8f94f-bcae-4ec6-b752-70d6cb59f932".

With Best Regards,

Elmer

Hello @thinkingserious,

When I use this code to send a transacational template , I get a success response but nothing is really sent. Nothing is received in the inbox and nothing in the activity section of SendGrid.

```const Sendgrid = require('@sendgrid/mail');
Sendgrid.setApiKey(SENDGRID_API_KEY);

const email =
{
to: '[email protected]',
from: SENDGRID_SENDER,
subject: 'Test',
template_id: 'd-128e110d98e040c6b81f4694d04e0572',
dynamic_template_data: {
subject: 'Coucou :)',
club_name: 'VTR School',
},
};

Sendgrid.send(email)
.then(m => {
console.log('Mail sent');
})
.catch(error => {

    //Log friendly error
    console.error(error.toString());

    //Extract error msg
    const { message, code, response } = error;

    //Extract response msg
    const { headers, body } = response;
});

```

However, all is fine when I use

text: 'and easy to do anywhere, even with Node.js',
or
html: '<strong>and easy to do anywhere, even with Node.js</strong>',

Do you have any idea for which reason?

Thanks

@milottit If you haven't figured it out already and for new comers who stumble along this ticket, I was getting the same successful result you were but no email response. How I resolved this, I used the following code.

Note below the following format in the 'dynamic_template_data' variable.

"name": 'Test'

I believe you need to send the variable you want to replace in the template as a string.

Sendgrid.setApiKey(SENDGRID_API_KEY);
const email =
{
    to: '[email protected]',
    from: SENDGRID_SENDER,
    subject: 'Test',
    template_id: 'd-128e110d98e040c6b81f4694d04e0572',
    dynamic_template_data: {
        "name": 'Test',
        "club_name": 'VTR School',
    },
};
Sendgrid.send(email)
    .then(m => {
        console.log('Mail sent');
    })
    .catch(error => {
        //Log friendly error
        console.error(error.toString());
    });

Hope this helps!

Was this page helpful?
0 / 5 - 0 ratings