How to use the Nodemailer library for sending HTML emails in Node.js



Image not found!!

Nodemailer is a popular library in Node.js for sending emails. To send HTML emails using Nodemailer, you can follow these steps:

  1. Install Nodemailer: Make sure you have Nodemailer installed in your project. You can install it using npm:
bash
npm install nodemailer
  1. Create a Nodemailer transporter: Set up a transporter with the SMTP details of your email provider. Here's an example using Gmail:
javascript
const 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', }, });
  1. Compose the email: Create an object with the details of your email, including the HTML content. For example:
javascript
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>', };
  1. Send the email: Use the transporter.sendMail method to send the email:
javascript
transporter.sendMail(mailOptions, (error, info) => { if (error) { console.error(error); } else { console.log('Email sent: ' + info.response); } });

Putting it all together:

javascript
const 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.