Node JS Send Email with Attachment Example

By Hardik Savani August 19, 2021 Category : Node JS

Hi,

In this tute, we will discuss node js send email with attachment. This post will give you simple example of how to send email with attachment in node js. if you want to see example of how to send attachment in mail using node js then you are a right place. We will look at example of send email with attachment in node.js. follow bellow step for node.js send email with attachment.

In this example we will use nodemailer npm package for sending email with attachment. here we will use sender as google gmail account and you have to add your email and password in sender details. we will add attachments parameter where we will add png image.

so let's follow simple step to send mail with node js.

Step 1: Create Node App

run bellow command and create node app.

mkdir my-app

cd my-app

npm init

Step 2: Install nodemailer

run bellow command and install nodemailer npm package.

npm install nodemailer -S

Step 3: Create server.js file

Here, you have to add "demo.png" image in your root folder. we added new parameter attachments where we pass that image. you can also add multiple files as attachment.

server.js

const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({

service: 'gmail',

auth: {

user: "[email protected]",

pass: "PASSWORD"

}

});

let message = {

from: "[email protected]",

to: "[email protected]",

subject: "Subject",

html: "<h1>Hello SMTP Email</h1>",

attachments: [

{

filename: 'demo.png',

path: __dirname + '/demo.png',

cid: 'uniq-demo.png'

}

]

}

transporter.sendMail(message, function(err, info) {

if (err) {

console.log(err);

} else {

console.log(info);

}

})

now you can simply run by following command:

node server.js

Output:

i hope it can help you...

Tags :