Sendgrid: render an ejs template and then send as an email.

So I have index.ejs which renders perfectly when I start my nodejs server:

<!DOCTYPE html>
<html>
    <head>
        <title<%= title %></title>
    </head>
    <body>
        <h1><%= title %></h1>
        <h3><%= yesterday %></h3>
        <h1> Number of Spins: <%= count %></h1>
        <h1> Active User Count: <%= userCount %></h1>
        <h1> Users that did not validate: </h1>
        <ul>

            <% for(var i=0; i<unvalid.length; i++) {%>

                <li><%= unvalid[i] %></li>
            <% } %>
        </ul>
    </body>
</html>

The thing is, I would like to send this on an email using Sendgrid. So far what i've been doing is using the .setHTML method to sort of "brute-force" it:

email.setHtml('<h1> Spotluck Daily Report </h1><h3>'+ yesterday + '</h3><h1> Number of Spins: '+cuenta+'</h1><h1> Active User Count: '+userCount+'</h1>' +'<h1> Users that did not validate: </h1>');

But this would never work because it would be unable to render the ejs for loop. So my question is: How do I tell the Sendgrid email to render my ejs and send it as an email without having to resort to .setHTML?

Upvotes: 0

Views: 1212

Answers (1)

eddiezane
eddiezane

Reputation: 916

You can achieve this using the ejs.render(str, subs) function inside of setHtml.

email.setHtml(ejs.render(yourTemplate, {foo: 'bar'}));

But I'd recommend using SendGrid's Template Engine since our node library supports it.

Upvotes: 3

Related Questions