Menu Close

How to Send an Email using Node.js?

5
(2)

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

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Share

Posted in NodeJs, NPM

Leave a Reply

Your email address will not be published. Required fields are marked *

You can also read...