Sending emails with Node.js is very easy using Nodemailer. Nodemailer provides several methods to send emails, but in this tutorial, I will explain how you can do it using your own email account. You can also refer to the Nodemailer documentation to explore different ways to send an email.
Step 1: Intall Nodemailer
First, install the nodemailer package using npm:
npm install nodemailer
Watch Video for more clarity
Step 2: Write the code
Here's a simple example that shows how to send an email
const nodemailer = require('nodemailer');
// Create a transporter using Gmail service
const transporter = nodemailer.createTransport({
service: 'gmail',
secure: true,
auth: {
user: "codewithdeepak.in@gmail.com", // your email
pass: "ywfknfrzpiswfbwo" // your app password (not your normal Gmail password)
}
});
// Create the email message
const message = {
from: "Learn From Codewithdeepak.in",
to: "codewithdeepak.in@gmail.com",
subject: "Learn How to Send Email Through Node.js Code",
html: "We are learning from Deepak Chaudhary
"
};
// Send the email
transporter.sendMail(message, (error, info) => {
if(error){
console.log(error);
}else{
console.log("Email sent: " + info.response);
}
});
✅ What’s Happening Here?
- We import Nodemailer and create a transporter using Gmail’s SMTP service. There are several ways to send email you can refer this
- We define the email content (from, to, subject, and HTML body).
- We call sendMail() to send the email, and check if there’s an error or success.
📌 Final Tip
If you’re using Gmail, make sure you generate an App Password from your Google Account (under Security > App Passwords) and use it instead of your main password.