How to Send Email in Node.js Using Nodemailer Package

dinapal_dev

Dina Pal

Posted on April 7, 2023

How to Send Email in Node.js Using Nodemailer Package

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:

  1. First, install Nodemailer using npm:
    npm install nodemailer

  2. Next, require Nodemailer in your Node.js file:
    const nodemailer = require('nodemailer');

  3. 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'
    }
});

Enter fullscreen mode Exit fullscreen mode
  1. 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'
};
Enter fullscreen mode Exit fullscreen mode
  1. 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);
    }
});

Enter fullscreen mode Exit fullscreen mode

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".

💖 💪 🙅 🚩
dinapal_dev
Dina Pal

Posted on April 7, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related