For this purpose, we will use a package called nodemailer. It is a module that makes email sending pretty easy. For using it, you will need to install by using the following command:
$ npm install nodemailer
Features of nodemailer module:
- It has zero dependencies and heavy security.
- You can use it hassle free whether its Azure or Windows box.
- It also comes with Custom Plugin support for manipulating messages.
Inorder to send email, create a file named index.js and write down the following code:
Filename: index.js
javascript
var nodemailer = require( "nodemailer" ); var sender = nodemailer.createTransport({ service: 'gmail' , auth: { user: 'username@gmail.com' , pass: 'your_password' } }); var mail = { from: "username@gmail.com" , to: "receiver's_username@gmail.com" , subject: "Sending Email using Node.js" , text: "That was easy!" }; sender.sendMail(mail, function (error, info) { if (error) { console.log(error); } else { console.log( "Email sent successfully: " + info.response); } }); |
Steps to run this program: In order to run this file, just Git Bash into your working directory and type the following command:
$ nodemon index.js
If you don’t have nodemon installed then just run the following command:
$ node index.js
To double-check its working you can go to the receiver’s mail and you will get the following mail as shown below:
What if you have multiple receiver?
Well in that case just add below code in your mail function:
to: 'first_username@gmail.com, second_username@gmail.com'
What if you want to send HTML formatted text to the receiver?
Well in that case just add below code in your mail function:
html: "<h1>GeeksforGeeks</h1><p>I love geeksforgeeks</p>"
What if you want to send an attachment to the receiver?
Well in that case just add below code in your mail function:
attachments: [ { filename: 'mailtrap.png', path: __dirname + '/mailtrap.png', cid: 'uniq-mailtrap.png' } ]
The final index.js file look like this:
Filename: index.js
javascript
var nodemailer = require( "nodemailer" ); var sender = nodemailer.createTransport({ service: 'gmail' , auth: { user: 'username@gmail.com' , pass: 'your_password' } }); var mail = { from: 'username@gmail.com' , to: 'first_username@gmail.com, second_username@gmail.com' , subject: 'Sending Email using Node.js' , text: 'That was easy!' , html: "<h1>GeeksforGeeks</h1> <p>I love geeksforgeeks</p> " , attachments: [ { filename: 'mailtrap.png' , path: __dirname + '/mailtrap.png' , cid: 'uniq-mailtrap.png' } ] }; sender.sendMail(mail, function (error, info) { if (error) { console.log(error); } else { console.log( 'Email sent successfully: ' + info.response); } }); |