Send Email in Nodejs With Nodemailer


By onjsdev

Introduction

In this blog post, we'll be discussing a Node.js & Express.js nodemailer module that allows sending emails using different hosts, such as Gmail and Yahoo, and supports different attachment options such as HTML, Text, and PDF.

We'll go through each function in the code to be provided and explain what it does. Let's get started.

What is Nodemailer?

Nodemailer is an easy-to-use library that allows sending email using Node.js. It provides a simple and powerful API for sending email using different transport methods, such as SMTP, Sendmail, and Amazon SES.

It supports multiple email services including Gmail, Yahoo, Outlook, and more. It offers a user-friendly interface and provides a flexible set of APIs that can be used to configure email messages.

Let's dive into the code

Importing The Nodemailer Package

This line imports the nodemailer library into your existing Node.js application, providing an effortless way to send emails using Node.js.

const nodemailer = require("nodemailer");

Define the SMTP Hosts for Different Email Providers

This object stores the SMTP hosts for different email providers. The keys of the object represent the provider name, and the values represent the corresponding SMTP host.

const HOSTS = {
  gmail: "smtp.gmail.com",
  yahoo: "smtp.mail.yahoo.com",
  outlook: "smtp.office365.com",
};

Create A Transporter

Transporter object in nodemailer proviede reusable coponent for sending a email.

The following function creates a transporter object that will be used to send email. It takes an object with three parameters: the SMTP host, the username, and the password. It then creates a nodemailer transporter object using the provided parameters.

function createTransporter({ host, user, pass }) {
  return nodemailer.createTransport({
    host: HOSTS[host] || HOSTS.gmail, // Default is gmail
    port: 465, // Port for secure connection
    secure: true,
    auth: {
      user,
      pass,
    },
  });
}

Create The Mail Options

The following function creates the mail options that will be used to send the email. It takes an object with six parameters:

  • the sender email address,
  • the recipient email address, t
  • the email subject,
  • the email type (text or html),
  • the email content,
  • an array of attachments.
function createMailOptions({ from, to, subject, type, content, attachments }) {
  let mailOptions = {
    from,
    to,
    subject,
  };

  switch (type) {
    case "text":
      mailOptions.text = content;
      break;

    case "html":
      mailOptions.html = content;
      break;
    default:
      mailOptions.text = content;
  }

  if (attachments && attachments.length > 0) {
    mailOptions.attachments = attachments.map((attachment, index) => ({
      filename: `${attachment.filename}.${attachment.file}`,
      path: attachment.path,
      cid: `file_${index}`,
    }));
  }

  return mailOptions;
}

It first creates an empty mailOptions object and sets the from, to, and subject properties. Then, depending on the email type, it sets either the text or html property of the mailOptions object.

If there are any attachments, it maps through the array and creates an object for each attachment. It sets the filename, path, and cid properties of each attachment object and adds them to the mailOptions object.

Finally, it returns the mailOptions object.

Send Email

The sendMail function takes in an options object containing the email details. It first checks that all required fields are present in the input object. It then calls the createTransporter function.

It then calls the createMailOptions function with the remaining fields to create a mail options object. Finally, it calls the transporter.sendMail() method with the mailOptions object to send the email.

If the email is sent successfully, the sendMail function logs a message containing the message ID of the sent email to the console.

async function sendMail(options) {
  const { host, user, pass, from, to, subject, type, content, attachments } =
    options;

  if (!host || !user || !pass || !from || !to || !subject) {
    throw new Error("Missing required parameters");
  }

  const transporter = createTransporter({ host, user, pass });
  const mailOptions = createMailOptions({
    from,
    to,
    subject,
    type,
    content,
    attachments,
  });

  const info = await transporter.sendMail(mailOptions);

  console.log("Message sent: %s", info.messageId);
}

Call The Send Email Function To Send Email In A NodeJs Application

That's all now we can call the sendMail function to send an email by providing required email informations. Let's send an email using gmail host:

// Example usage:
sendMail({
  host: "gmail",
  user: "your-emaill",
  pass: "your-pass",
  from: "sender",
  to: "receiver",
  subject: "Test email",
  content: "Hello",
  attachments: [
    {
      file: "png",
      filename: "myimage",
      path: "path/to/image",
    },
  ],
});

Note that, using gmail host is needed a app password, which can be generated your user google account. After generating an app password you can replace it with the password field.

After sending email content and attachments, you will see the console message on you terminal.

Conclusion

Overall, this guide provides a straightforward and flexible way to send emails using Node.js with the nodemailer package, with support for different email providers, authentication, and attachment options.

Thank you for reading.