Menu Close

How to Send an Email using Node.js?

Codeamend

NodeJs is an open-source run-time environment that organizes everything you would like to execute a program written in JavaScript. It’s used for running scripts on the server to render content before it’s delivered to an internet browser.

NPM stands for Node Package Manager, which is an application and repository for developing and sharing JavaScript code.

Follow the below steps to send the email.

The Nodemailer module makes it easy to send emails from your computer.

Install Nodemailer using npm install

C:\users\codeamend>npm install nodemailer 

After you have install the Nodemailer module, you can include the module in any application.

Send an Email to One Receiver

Once you are installed the nodemailer package you are ready to send emails from your server.

Use the username and password from your selected email provider to send an email.

The following codes will show you how to use your Gmail account to send an email:

var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});

var mailOptions = {
  from: 'youremail@gmail.com',
  to: 'admin@codeamend.com',
  subject: 'Test Email using Node.js',
  text: 'That was easy!'
};

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

Send an Email to Multiple Receivers

var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});

var mailOptions = {
  from: 'youremail@gmail.com',
  to: 'admin@codeamend.com, info@codeamend.com',
  subject: 'Test Email using Node.js',
  text: 'That was easy!'
};

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

View More Details about the nodemailer package – https://www.npmjs.com/package/nodemailer

Posted in NodeJs, NPM

You can also read...