How to Send Email with Attachment in Node JS ?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i will show you How to Send Email with Attachment in Node JS ? In this tutorial , we will know about node js send email also with attachment. This post i will give you a very simple example of how to send an email with attachment by using node js. if you want to see an example about how to send attachment in mail by using node js then i hope you are in right place. Here we will look at an example of send email also with attachment by using node.js. Just need to follow the bellow step for node.js send email with attachment.

So in this example i am using nodemailer npm package for sending my email with an attachment. Now here i will use sender as google gmail account and if you have to add your email and password in your sender details.

Now so let’s start and follow the simple step to send mail with node js.

Step 1: Create Node App

Need to run bellow command and the create node app.

mkdir my-app
cd my-app  
npm init
Step 2: Install nodemailer

Now need to run bellow command and then install nodemailer npm package.

npm install nodemailer -S
Step 3: Create server.js file

Here, we have to add the “srtest.png” image in our root folder. And then we will added new parameter attachments where we pass that image. So we can also add the multiple files as attachment.

server.js

const nodemailer = require('nodemailer');
  
let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: "srsagor@gmail.com",
            pass: "PASSWORD"
        }
});
  
let message = {
    from: "srsagor@email.com",
    to: "srsagor007@gmail.com",
    subject: "Subject",
    html: "<h1>Hello Test SMTP Email</h1>",
    attachments: [
        {
            filename: 'demo.png',
            path: __dirname + '/srtest.png',
            cid: 'uniq-srtest.png'
        }
    ]
}
  
transporter.sendMail(message, function(err, info) {
  if (err) {
    console.log(err);
  } else {
    console.log(info);
  }
})

now we can simply run our project by using following command:

node server.js

Read Also :Laravel Join with Subquery in Query Builder Example

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →