0

I have created a very simple "Hello world" template in sendgrid.

Now i wish to send an email using this template from my node server

normally to send a mail i have to do something like this:

 email.send = function (Object) { sendgrid.send({ from: Object.from, to: Object.to, subject: Object.subject, html: Object.html, text: Object.text }, function (err, json) { if (err) { console.log('SendGrid error:'); return console.error(err); } console.log('SendGrid success'); }); }; 

However im not sure how i can include my template?

I can't seem to find documentation on the subject so i hope you guys are able to help me.

4
  • Not clear on what you mean by "send an email using this template". Commented Jun 6, 2016 at 10:36
  • @Paul in sengrid you can create templates i wish to send a mail using that template Commented Jun 6, 2016 at 10:39
  • 4
    You might be looking for this github.com/sendgrid/sendgrid-nodejs#templates Commented Jun 6, 2016 at 10:42
  • @Sami Yep your correct i found it! Commented Jun 6, 2016 at 11:08

1 Answer 1

1

I used 'email-templates-v2' for my project. First compile your template file like this:

var EmailTemplate = require('email-templates-v2').EmailTemplate; var templateDir = constants.email_templates_path + 'user-line-won'; var userWonTemplate = new EmailTemplate( templateDir ); 

Now, for passing context data to your template, create a context object. For example:

var templateContext = {}; templateContext.user = req.session.user; templateContext.campaign = req.campaign; templateContext.project = req.project; 

Now, render the template and send the mail in the callback function. You get the compiled template in the success callback:

userWonTemplate.render(templateContext, function (err, results) { if( err ) { console.log( err ); res.render('error', {'title': 'Error', 'error': err, 'session': req.session}); } else { var nodemailer = require("nodemailer"); var mailTransport = nodemailer.createTransport(); var mailOptions = { from: fromEmail, to: toEmail, subject: subjectEmail, text: "A user subject line has won.\n", html: results.html }; mailTransport.sendMail(mailOptions, function(error, response){ if(error){ console.log(error); }else{ console.log("Message sent: " + response.message); } }); next(); } }); 

I have used nodemailer, but passing the compiled html to sendgrid should work similarly.

Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what i want to avoid (if i can) using this will require alot of code where i hoped i could just use sendgrid's api to use the template i made there to keep my code neat and tiny
yes, @Sami pointed this out clearly in his comment. My answer is irrelevant in this context. :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.