Sun. Nov 17th, 2024

How to send Email using Nodemailer in Nodejs

Nodemailer

Sending emails with Node.js is a common requirement, and one of the popular libraries to accomplish this is nodemailer. Here’s a step-by-step tutorial on how to send emails using Node.js with nodemailer.

Step 1: Set Up Your Node.js Project

  1. Initialize Your Project: If you don’t already have a Node.js project, create a new one.

  mkdir my-email-project
  cd my-email-project
  npm init -y

Install Nodemailer: Install nodemailer using npm.

npm install nodemailer

Step 2: Create an Email Sending Script

  1. Create a File: Create a file named sendEmail.js in your project directory.

touch sendEmail.js

Write the Code: Open sendEmail.js in your favorite editor and add the following code.

const nodemailer = require(“nodemailer”);
// Create a transporter object using SMTP transport
let transporter = nodemailer.createTransport({
  service: “gmail”, // Use the email service you want to use (e.g., ‘gmail’, ‘yahoo’, etc.)
  auth: {
    user: “your-email@gmail.com”, // Replace with your email address
    pass: “your-email-password”, // Replace with your email password or app password
  },
});
// Set up email data
let mailOptions = {
  from: “your-email@gmail.com”, // Sender address
  to: “recipient-email@example.com”, // List of recipients
  subject: “Hello ✔”, // Subject line
  text: “Hello world?”, // Plain text body
  html: “<b>Hello world?</b>”, // HTML body
};
// Send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    return console.log(“Error occurred:”, error);
  }
  console.log(“Message sent successfully:”, info.response);
});

Step 3: Test the Script

  1. Run the Script: Execute your script using Node.js.

node sendEmail.js

Step 4: Handling Security and Environment Variables

  1. Using Environment Variables: To avoid hardcoding sensitive information like your email password, you can use environment variables. Create a .env file in your project directory.

futuredecode.com

By futuredecode.com

we are future decoder's

Related Post

One thought on “How to send Email using Nodemailer in Nodejs”
  1. I haven’t checked in here for some time because I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my everyday bloglist. You deserve it my friend 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *