How To send emails using Node.js with Nodemailer npm

How To send emails using Node.js with Nodemailer npm

How To send emails using Node.js with Nodemailer npm

In this Node.js tutorial, I will tell you how to send email in Node.js using Nodemailer module.

This makes it very easy to send emails from node application.

You can easily installed the Nodemailer module using npm command with Node.js

Nodemailer is licensed under MIT license.

The best thing is it support unicode, that means you can use any characters including emoji.

You can send raw text as well HTML content.

You can embed images in HTML, and also can add attachments to messages.

Nodemailer support different transport methods - SMTP, Sendmail and Amazon SES.

In this example, I am sharing simple code to send email in node application using Nodemailer module.

Installation

Run following command to install Nodemailer :

npm install nodemailer --save

Require the Nodemailer module in your js file :

var nodemailer = require('nodemailer');

  1. function sendMail(to,subject,message)
  2. {
  3. var smtpConfig = {
  4. service: 'Gmail',
  5. auth: {
  6. user: 'username@gmail.com',
  7. pass: 'xxxxxx'
  8. }
  9. };
  10. var transporter = nodemailer.createTransport(smtpConfig);
  11. var mailOptions = {
  12. from: '"Sender Name" <sender@gmail.com>', // sender address
  13. to: to, // list of receivers
  14. subject: subject, // Subject line
  15. text: 'Hello world ?', // plaintext body
  16. html: message // html body
  17. };
  18. transporter.sendMail(mailOptions, function(error, info){
  19. if(error)
  20. {
  21. return console.log(error);
  22. }
  23. else
  24. {
  25. return console.log(info.response);
  26. }
  27. });
  28. }
  29. var message = '<p>This is HTML content</p>';
  30. sendMail('ajay.agrahari09@gmail.com','Welcome to ExpertPHP.in',message);

Phone: (+91) 8800417876
Noida, 201301