Nodemailer is a popular library in Node.js for sending emails. To send HTML emails using Nodemailer, you can follow these steps:
bashnpm install nodemailer
javascriptconst nodemailer = require('nodemailer');
// Create a transporter using SMTP details
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your_email@gmail.com',
pass: 'your_email_password',
},
});
javascriptconst mailOptions = {
from: 'your_email@gmail.com',
to: 'recipient_email@example.com',
subject: 'Subject of the email',
html: '<p>Your HTML content goes here</p>',
};
transporter.sendMail
method to send the email:javascripttransporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Putting it all together:
javascriptconst nodemailer = require('nodemailer');
// Create a transporter using SMTP details
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your_email@gmail.com',
pass: 'your_email_password',
},
});
// Compose the email
const mailOptions = {
from: 'your_email@gmail.com',
to: 'recipient_email@example.com',
subject: 'Subject of the email',
html: '<p>Your HTML content goes here</p>',
};
// Send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Make sure to replace 'your_email@gmail.com', 'your_email_password', and 'recipient_email@example.com' with your actual email and password, and the recipient's email address.