cusejuice
cusejuice

Reputation: 10691

Use email template for contact form using Express/Sendgrid

I have a simple contact form using the Node Sendgrid helper library.

I would like to use a template email/contact.jade that compiles to HTML and adds the right context. I know it needs to go in the payload.html value, however I'm stuck on how to send the email with the template.

routes.js

app.route('/contact')
  .post(function(req, res) {
    var template = 'email/contact.jade';

    var payload = {
      to: req.body.email,
      from: '[email protected]',
      subject: req.body.subject,
      html: req.body.message
    };

    var email = new sendgridClient.Email(payload);

    sendgridClient.send(email, function(err, json) {
      if (err) { 
        return console.error(err);
      } else {
        res.redirect('/thanks');
      }
    });
  });

email/contact.jade

p Thanks
p Name {{ name }}
p Email {{ email }}
p Subject {{ subject }}
p Message {{ message }}

Upvotes: 2

Views: 937

Answers (1)

Andrew Lavers
Andrew Lavers

Reputation: 8151

First I'm not sure your jade syntax is correct. You could try this instead:

email/contact.jade

p Thanks
p Name #{name}
p Email #{email}
p Subject #{subject}
p Message #{message}

And to render this into HTML:

var jade = require('jade');
var templatePath = __dirname + '/contact.jade';

app.route('/contact')
  .post(function(req, res) {    
    var payload = {
      to: req.body.email,
      from: '[email protected]',
      subject: req.body.subject,
      html: jade.renderFile(templatePath, req.body)
    };
    //...
  });

Upvotes: 1

Related Questions