Node JS Send Email with Attachment Example
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: "your_gmail_account@gmail.com",
pass: "PASSWORD"
}
});
let message = {
from: "from@email.com",
to: "receiver_email@gmail.com",
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get Current Date and Time in Node JS?
- How to Remove Element from Array in Node JS?
- How to Push Element in Array in Node JS?
- Node JS Sort Array of Objects by Value Example
- Node JS Foreach Loop Array Example
- How to Create and Use .env File in Node JS?
- Node JS Make HTTP Put Request Example
- Node JS Make HTTP Delete Request Example
- Node JS Make Http Get Request with Parameters Example
- How to make an HTTP POST request in Node JS?
- Node JS Multer Rename Uploaded File Example