Programming Tutorials

Send email from node.js application

By: William Alexander in node.js Tutorials on 2018-08-04  

In this tutorial, we will learn how to send emails from node.js applications. In any application, sending out alerts and notifications via email becomes an integral part. Node.js has a package for sending mails and it is called nodemailer. 

What is npm?

npm is an acronym for node.js package manager. There are thousands of free packages available for download from npmjs.com. As part of node.js installation, npm is also installed automatically. Packages are nothing but JavaScript libraries and also called modules. While node.js default installation comes with many in-built packages, often times you may need to download and install packages that are used in some use cases. Sending emails from a node.js application is an example. 

To install a new package, just run the command 'npm install <package-name>' in the command prompt.

C:\Users\username>npm install nodemailer

This will automatically download and install nodemailer package that can be used from your node.js applications by calling the 'require()' command.

Sending emails from node.js application

Create a new file named 'sendemail.js'

var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '[email protected]',
    pass: 'yourpassword'
  }
});

var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Sending Email from Node.js',
  html: '<h1>Hello friend</h1><p>This is an html formatted email content</p>';
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

As usual, you can run this script by running the command 'node sendemail.js'

In this script, we just used the nodemailer package and created a transporter using a gmail account. So you have to replace the [email protected] and yourpassword with your actual gmail username and password. So the nodemailer will use your gmail account to send the email. You can send html formatted email as shown in the example. If you just want to send text format, just replace the 'html' with 'text'. example text: 'This is a normal text email content';






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in node.js )

Latest Articles (in node.js)