Nodemailer and sending Emails

Aditya kumar
Last Updated: May 13, 2022

Introduction

Nodemailer is a Node.js module that makes it simple to send emails from a server. Whether you want to interact with your users or simply inform yourself when something goes wrong, the mail is one of your alternatives.

The project began in 2010 when there was no logical way to send email messages, and it is now the default solution for most Node.js users.

 

Source: Nodemailer

 

How to Begin Using Nodemailer

First, we'll use Express to put up our Node.js boilerplate. Run the following instructions to ensure that Node and npm are installed:

node -v 
npm -v

 

You're OK to go if both of these commands return a version. Install what's missing if it's not already installed.

 

Make a folder for your project. NodemailerProject will be used.

 

mkdir nodemailerProject

 

Our project will be started with a pacakge.json file.

 

After that, we'll need to install Express by following these steps:

 

npm install express

 

Open the file that you specified as your entry point (the default is index.js) and paste the following code in it:

 

const express = require('express')
const app = express()
const port = 3000


app.listen(port, () => {
  console.log(`nodemailerProject is listening at http://localhost:${port}`)
})

 

Index.js

To start a simple server with Express, you'll need the following. Run the following command to see if it's working correctly:

node index.js

npm install nodemailer

 

Requirements

Node.js v6.0.0 or newer is required. That is all there is to it.

You can use Nodemailer if you have Node.js version 6 or higher installed. There are no specific platform or resource requirements. Callbacks and Promises are supported by all public Nodemailer functions (if callback is omitted). If you wish to utilise async..await with Nodemailer, you'll need at least Node v8.0.0.

 

How Do We Install Nodemailer?

The API for Nodemailer is quite simple, and it only asks us to accomplish the following:

  1. To begin, make a Transporter object.
  2. Create an Object called MailOptions.
  3. Use the Transporter.sendMail function to send an email.

 

To make a transporter object, perform these steps:

The most specific transporter is SMTP, which we'll go over in more depth and explain with several instances below. However, there is a list of other options:

  • Transports built-in
  • For simple messages, sendmail is a typical sendmail command. It works similarly to PHP's mail() function.
  • SES, which allows you to send enormous amounts of email utilising Amazon SES.
  • To return messages, use a stream, which is a buffer for testing purposes.
  • External transport is available. Simply put, you can design your mode of transportation.

Everything is relatively essential with SMTP. Set the host, port, authentication information, and method, and you're done. At this point, it's also a good idea to double-check that the SMTP connection is working correctly: use the verify(callback) method to validate the connection and authentication.

 

let transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        type: 'OAuth2',
        user: process.env.MAIL_USERNAME,
        pass: process.env.MAIL_PASSWORD,
        clientId: process.env.OAUTH_CLIENTID,
        clientSecret: process.env.OAUTH_CLIENT_SECRET,
        refreshToken: process.env.OAUTH_REFRESH_TOKEN
      }
    });

 

Next, we'll build the mailOptions object, containing information about where and how to send the email.

At this stage, we should define the sender, message recipients, and the body of our message.

Remember that Unicode is supported, which means you can use emojis!

No additional characteristics are necessary to send an HTML-formatted message; simply include your HTML body in the message with an HTML attribute. Attachments and photos can be embedded in advanced templates. First, consider the following example of simple message options:

 

let mailOptions = {
      from: tomerpacific@gmail.com,
      to: tomerpacific@gmail.com,
      subject: 'Nodemailer Project',
      text: 'Hi from your nodemailer project.'
    };

 

This object can contain many more fields and even numerous recipients, but we're not going to get into that right now.

 

Finally, we'll use the method sendMail:

 

transporter.sendMail(mailOptions, function(err, data) {
      if (err) {
        console.log("Error " + err);
      } else {
        console.log("Email sent successfully");
      }
    });

 

When you run your app, you'll notice that your inbox has been updated with a new email.

 

This is an example of sending an email with plain text and an HTML body.

 

"use strict";
const nodemailer = require("nodemailer");

// async..await is not allowed in global scope, must use a wrapper
async function main() {
  // Generate test SMTP service account from ethereal.email
  // Only needed if you don't have a real mail account for testing
  let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: testAccount.user, // generated ethereal user
      pass: testAccount.pass, // generated ethereal password
    },
  });

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: '"Fred Foo 👻" <foo@example.com>', // sender address
    to: "bar@example.com, baz@example.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world?", // plain text body
    html: "<b>Hello world?</b>", // html body
  });

  console.log("Message sent: %s", info.messageId);
  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

  // Preview only available when sending through an Ethereal account
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

main().catch(console.error);

 

Nodemailer Features

  • A single module with no dependencies - the code is easily auditable because no dark corners exist.
  • No one likes RCE vulnerabilities; thus, there's a lot of emphasis on security.
  • Unicode allows you to use whatever character you choose, including emoji.
  • There are no constructed dependencies, so you can install it using npm on Windows just like any other module. It's simple to use from Azure or your Windows machine.
  • Use both HTML and plain text for your material.
  • Messages with attachments
  • HTML content with embedded picture attachments — your design is not obstructed.
  • TLS/STARTTLS ensures secure email delivery.
  • In addition to the built-in SMTP support, you can use a variety of transport mechanisms.
  • For altering communications, sign messages with DKIM Custom Plugin support.
  • OAuth2 authentication that is safe
  • For SMTP connections, proxies are used.

 

Options for debugging in Nodemailer

We've gone over the basics of sending emails using Nodemailer, including how to add different objects to HTML messages, and there's one more option worth mentioning: leverage native debugging for successful mail sending testing.

With Nodemailer, it's as simple as setting both debug and logger to true, and you'll be able to view all of the data sent to the server as an output in the console. This way, you'll be able to examine the email sending process and swiftly correct any issues that arise.

Specify debug options in the transporter section of the mail script in your Node.js app:

var transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "1a2b3c4d5e6f7g",
    pass: "1a2b3c4d5e6f7g"
  },
  debug: true, // show debug output
  logger: true // log information in console
});

 

What you'll find in the console is as follows:

 

[2018-12-28 18:05:10] DEBUG Creating transport: nodemailer (5.0.0; +https://nodemailer.com/; SMTP/5.0.0[client:5.0.0])
[2018-12-28 18:05:10] DEBUG Sending mail using SMTP/5.0.0[client:5.0.0]
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] Resolved smtp.mailtrap.io as 54.87.153.8 [cache miss]
[2018-12-28 18:05:10] INFO  [nJWMVEIqQCE] Connection established to 54.87.153.8:2525
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 220 smtp.mailtrap.io ESMTP ready
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] C: EHLO [127.0.0.1]
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 250-smtp.mailtrap.io
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 250-SIZE 5242880
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 250-PIPELINING
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 250-ENHANCEDSTATUSCODES
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 250-8BITMIME
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 250-DSN
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 250-AUTH PLAIN LOGIN CRAM-MD5
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 250 STARTTLS
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] C: STARTTLS
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] S: 220 2.0.0 Start TLS
[2018-12-28 18:05:10] INFO  [nJWMVEIqQCE] Connection upgraded with STARTTLS
[2018-12-28 18:05:10] DEBUG [nJWMVEIqQCE] C: EHLO [127.0.0.1]
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250-smtp.mailtrap.io
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250-SIZE 5242880
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250-PIPELINING
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250-ENHANCEDSTATUSCODES
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250-8BITMIME
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250-DSN
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250 AUTH PLAIN LOGIN CRAM-MD5
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] SMTP handshake finished
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] C: MAIL FROM:<from@example.com>
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250 2.1.0 Ok
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] C: RCPT TO:<user1@example.com>
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] C: RCPT TO:<user2@example.com>
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250 2.1.0 Ok
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 250 2.1.0 Ok
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] C: DATA
[2018-12-28 18:05:11] DEBUG [nJWMVEIqQCE] S: 354 Go ahead
…
[2018-12-28 18:05:12] DEBUG [nJWMVEIqQCE] S: 250 2.0.0 Ok: queued
[2018-12-28 18:05:12] DEBUG [nJWMVEIqQCE] Closing connection to the server using "end"
Message sent: <74bfe12e-92fa-91f8-8643-a166b66c62d7@example.com>
[2018-12-28 18:05:12] INFO  [nJWMVEIqQCE] Connection closed

 

Capabilities of Nodemailer

We went over how to use Nodemailer to compose and send emails using SMTP, playing with various sorts of content such as HTML, tables, lists, attachments, and embedded images.

What's excellent about Nodemailer is that it gives you many different options and settings to customise every aspect of your email. Additional plugins extend Nodemailer's functionality with email templates, mailer classes and utilities, loggers and helpers to send authentication emails, modules to send emails using Gmail, NodeJS implementations of many APIs, and many others are available.

It's a piece of cake to send emails with Nodemailer. It is simple and devoid of stumbling blocks. It's a winning formula for email marketing!!

 

Frequently Asked Questions

1. What is Nodemailer?

Nodemailer is a single Node.js module for sending emails that have no dependencies. Its key characteristics include (but are not limited to) the following:

  • Platform-Independent
  • TLS/STARTTLS email delivery and DKIM email authentication are two examples of security.
  • Unicode support
  • Embedded picture attachments and HTML content
  • SMTP isn't the only mode of transport supported. 

 

2. What is the best way to test emails with Nodemailer?

We'll utilise Mailtrap, an online tool for complicated email testing in a pre-production environment, to test emails sent with Nodemailer. It will intercept our communications, display them as they would appear in a genuine email client, and assist in their analysis and debugging. Mailtrap now supports Bcc testing and allows you to discuss your email testing results with other members of your team, as well as forward emails to genuine verified addresses.

Even If you don't already have an account, it just takes a few minutes to create one. Mailtrap works as a standard SMTP server. Sign up quickly (it's free), then navigate to your Inbox's SMTP settings tab, copy the relevant settings, and paste them into your application script.

Mailtrap has a ready-to-use Nodemailer integration: Insert it into your application code by selecting it from the Integrations section. It already has properties for transporter and syntaxis:

 

var transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "1a2b3c4d5e6f7g", //generated by Mailtrap
    pass: "1a2b3c4d5e6f7g" //generated by Mailtrap
  }
});

 

Otherwise, you can use Ethereal's auto-generated email test accounts, which is a phoney SMTP service geared primarily towards Nodemailer users.

Nodemailer recently released NodemailerApp. It's a Sendmail substitute, but it's first and foremost intended for email debugging. NodemailerApp includes SMTP and POP3 local servers, as well as a catchall email domain service and email preview.

 

3. How do we use Nodemailer?

To get started with Nodemailer, you'll need Node.js version 6.0 or higher. You should also install Nodemailer, which is simple to do using the npm or Yarn, package managers. In the Node.js command prompt, type the following command:

 

npm install nodemailer 
Or
yarn add nodemailer

 

After you've finished it, paste it into your application like this:

var nodemailer = require('nodemailer');

 

Likewise, if you're using ES modules, this:

import nodemailer from ‘nodemailer’;

 

There are three primary steps to sending a message with Nodemailer:

  1. Make a transporter for Nodemailer.
  2. Set message options for Nodemailer.
  3. With sendMail(), you can send a message.

 

Key takeaways

The goal of this article is to demonstrate how to utilise Nodemailer, and how we can send emails by using Nodemailer. We'll concentrate on SMTP and HTML, but we'll go through all of Nodemailer's features as well. In addition, this article will assist you in creating and testing email messages for use with your Node.js application. 

If you want to start with nodemailer and sending emails then you can learn it with the help of video by clicking here Learn Parallel Jobs + Mail.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think