How to Send Email in Node.js Using Nodemailer Package
Dina Pal
Posted on April 7, 2023
Sending an email in Node.js
requires an email server and a Node.js package for sending emails. One popular package for this is Nodemailer. Here's a basic example of how to send an email using Nodemailer in Node.js:
First, install Nodemailer using npm:
npm install nodemailer
Next, require Nodemailer in your Node.js file:
const nodemailer = require('nodemailer');
Create a transport object using the SMTP protocol and your email provider's credentials. Here's an example using Gmail:
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-email-password'
}
});
- Define the email message object, including the sender, recipient, subject, and message body:
let mailOptions = {
from: 'your-email@gmail.com',
to: 'recipient-email@example.com',
subject: 'Test Email',
text: 'This is a test email from Node.js'
};
- Use the
transporter.sendMail()
method to send the email:
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Note: You may need to allow access to less secure apps on your Gmail account. To do this, go to your Google Account settings, select Security, and turn on "Less secure app access".
Posted on April 7, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.