Integrate nodemailer with smtp

Sending email with nodemailer using smtp is super simple. If the configuration is set right then it works like charm. In my case it worked in one shot. First of all we need to install nodemailer using following command:
sudo npm install nodemailer
Now include the nodemailer like below:
var nodemailer = require('nodemailer');
Now we are ready to use nodemailer object. To create a smtp transport object use to set some configuration like below:
var smtpConfig = {
  host: <your-host-name>,
  port: 465,
  secure: true, // use SSL
  auth: {
    user: <your-user-name>,
    pass: <your-user-password>
  }
};
var smtpTransport = nodemailer.createTransport(smtpConfig);
Now we set to call sendmail method of smtp transport. The transport all needs proper email configuration to send email. See the following function call:
  var mailOptions = {
    to: 'to-address',
    from: 'from-address', // This from email has to be verified with the smtp config host
    subject: 'email-subject',
    html: 'email-body'
  };
  smtpTransport.sendMail(mailOptions, function (err) {
    if (!err) {
      console.log('Success');
    } else {
      console.log(err);
    }
  });

Comments