Nodemailer: Sending Emails with Ease in Node.js

Discover how to use Nodemailer, a popular Node.js module for sending emails with ease. Learn how to install Nodemailer, configure an email address, send emails with attachments, and debug email sending processes in this comprehensive guide.

· 1 min read

Introduction

Nodemailer is a popular Node.js module that allows you to send emails from your server with ease. It is a single module with zero dependencies, designed for sending emails and providing security features such as email delivery with TLS/STARTTLS and DKIM email authentication.

Configuring an Email Address for Nodemailer

To use Nodemailer, you need an email address to send emails from. You can use any email service, but if you're using a Gmail account, there are some important steps to configure your account [1].

Sending Emails with Nodemailer

To send emails with Nodemailer, follow these three main steps:

  1. Install Nodemailer using npm install nodemailer.
  2. Create a transporter object with the necessary configuration, such as SMTP settings and authentication credentials.
  3. Send the email using the sendMail method on the transporter object.

Here's an example of how to send an email using Nodemailer:

const nodemailer = require("nodemailer");

// Create a transporter object
const transporter = nodemailer.createTransport({
  host: "smtp.example.com",
  port: 587,
  secure: false,
  auth: {
    user: "your-email@example.com",
    pass: "your-password"
  }
});

// Send the email
transporter.sendMail({
  from: "your-email@example.com",
  to: "recipient@example.com",
  subject: "Hello",
  text: "Hello world!"
}, (err, info) => {
  console.log(err || info);
});

Adding Attachments to Emails

To add attachments to your email, include an attachments array in the mailOptions object:

var mailOptions = {
  // ...
  attachments: [
    { filename: "pic-1.jpeg", path: "./attachments/pic-1.jpeg" }
  ],
}

Debugging Email Sending with Nodemailer

To debug email sending, set both debug and logger to true in the transporter configuration:

var transport = nodemailer.createTransport({
  // ...
  debug: true, // show debug output
  logger: true // log information in console
});

This will output detailed information about the email sending process, allowing you to quickly identify and fix any errors.

Conclusion

By following this guide, you've learned how to use Nodemailer to send emails from your Node.js application, add attachments to your emails, and debug the email sending process. Remember to handle your email credentials and tokens securely and consider error handling to ensure your email-sending process is robust.