Nodemailer is the Node.js npm module that allows you to send email easily.
Install nodemailer
npm install nodemailer
Include the nodemailer module in the code using require(‘nodemailer’).
Use nodemailer.createTransport() function to create a transporter who will send mail. It contains the service name and authentication details (user ans password).
Declare a variable mailDetails that contains the sender and receiver email id, subject and content of the mail.
Use mailTransporter.sendMail() function to send email from sender to receiver. If message sending failed or contains error then it will display error message otherwise message send successfully.
Example:
const nodemailer = require(‘nodemailer’);
let mailTransporter = nodemailer.createTransport({
service: ‘gmail’,
auth: {
user: ‘xyz@gmail.com’,
pass: ‘*************’
}
});
let mailDetails = {
from: ‘xyz@gmail.com’,
to: ‘abc@gmail.com’,
subject: ‘Test mail’,
text: ‘Node.js test email’
};
mailTransporter.sendMail(mailDetails, function(err, data) {
if(err) {
console.log(‘Error Occurs’);
} else {
console.log(‘Email sent successfully’);
}
});