11

I recently started programming my first node.js. I can't find any modules from node that is able to send html page as email. please help, thanks!

2 Answers 2

18

I have been using this module: https://github.com/andris9/Nodemailer

Updated example(using express and nodemailer) that includes getting index.jade template from the file system and sending it as an email:

var _jade = require('jade');
var fs = require('fs');

var nodemailer = require("nodemailer");

var FROM_ADDRESS = '[email protected]';
var TO_ADDRESS = '[email protected]';

// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Gmail",
    auth: {
        user: "[email protected]",
        pass: "PASSWORD"
    }
});

var sendMail = function(toAddress, subject, content, next){
  var mailOptions = {
    from: "SENDERS NAME <" + FROM_ADDRESS + ">",
    to: toAddress,
    replyTo: fromAddress,
    subject: subject,
    html: content
  };

  smtpTransport.sendMail(mailOptions, next);
}; 

exports.index = function(req, res){
  // res.render('index', { title: 'Express' });

  // specify jade template to load
  var template = process.cwd() + '/views/index.jade';

  // get template from file system
  fs.readFile(template, 'utf8', function(err, file){
    if(err){
      //handle errors
      console.log('ERROR!');
      return res.send('ERROR!');
    }
    else {
      //compile jade template into function
      var compiledTmpl = _jade.compile(file, {filename: template});
      // set context to be used in template
      var context = {title: 'Express'};
      // get html back as a string with the context applied;
      var html = compiledTmpl(context);

      sendMail(TO_ADDRESS, 'test', html, function(err, response){
        if(err){
          console.log('ERROR!');
          return res.send('ERROR');
        }
        res.send("Email sent!");
      });
    }
  });
};

I'd probably move the mailer part to its own module but I included everything here so you can see it all together.

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

6 Comments

I have used it too but it is can not sent a complicated template
What do you mean by complicated template? As long as your template is compiled to a string I don't see why it wouldn't work.
awesome, your example works so great. It is easy to understand. Again, thanks so much!
How can we set src= for '<img src="smiley.gif" alt="Smiley face" height="42" width="42">'. I think we will attach file smiley.gif to email. Is that right?. Do you have example code?, thanks!
its fine but how to load my custom css and image in the users mail... they are not loading :((
|
6

You can use nodemailer and nodemailer-express-handlebars modules do this:

var nodemailer = require('nodemailer');
var mailerhbs = require('nodemailer-express-handlebars');

var mailer = nodemailer.createTransport({
    service: Gmail,  // More at https://nodemailer.com/smtp/well-known/#supported-services
    auth: {
        user: [[email protected]], // Your email id
        pass: [PASSWORD] // Your password
    }
});

mailer.use('compile', mailerhbs({
    viewPath: 'templates/default/emails', //Path to email template folder
    extName: '.hbs' //extendtion of email template
}));

In router post you can use:

mailer.sendMail({
            from: 'Your name [email protected]',
            to: user.local.email,
            subject: 'Reset your password',
            template: 'password_reset', //Name email file template
            context: { // pass variables to template
                hostUrl: req.headers.host,
                customeName: user.info.firstname + ' ' + user.info.lastname,
                resetUrl: req.headers.host + '/users/recover/' + token,
                resetCode: token
            }
        }, function (err, response) {
            if (err) {
                res.send('Error send email, please contact administrator to best support.');
            }
            res.send('Email send successed to you email' + req.body.email + '.');
            done(err, 'done');
        });

In hbs template you can use variables:

{{var from context}}

hope blocks of code to help you.

5 Comments

its necessary to give extName only .hbs ? can i use .html ?
You can use the syntax of the engine template to display a variable in .html
i am using html view engine. can't access context variable in html file. how can i do?
i passed like this context : {name : 'myname'}
how can i use name ? in html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.