How to send Attachments and Email using nodemailer in Node.js ?
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 it is Azure or Windows box.
- It also comes with Custom Plugin support for manipulating messages.
In order to send an email, create a file named index.js and write down the following code:
Filename: index.js
javascript
const nodemailer = require( "nodemailer" ); let sender = nodemailer.createTransport({ service: 'gmail' , auth: { user: 'username@gmail.com' , pass: 'your_password' } }); let 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 receivers?
Well in that case just add the below code to 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 the below code to your mail function:
html: "<h1>w3wiki</h1><p>I love w3wiki</p>"
What if you want to send an attachment to the receiver?
Well in that case just add the below code to your mail function:
attachments: [ { filename: 'mailtrap.png', path: __dirname + '/mailtrap.png', cid: 'uniq-mailtrap.png' } ]
The final index.js file looks like this:
Filename: index.js
javascript
let nodemailer = require( "nodemailer" ); let sender = nodemailer.createTransport({ service: 'gmail' , auth: { user: 'username@gmail.com' , pass: 'your_password' } }); let 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>w3wiki</h1>< p > I love w3wiki</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); } }); |
Contact Us