Node.js + Nodemailer : How to send Emails via SMTP with Nodemailer

Nodemailer is a Node.js package that makes sending emails as simple as pie. 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.

This article aims to demonstrate and explain how to send emails via SMTP with Nodemailer.

In short, to send messages via SMTP using Nodemailer, you will need to follow these steps:

  1. Download and Install Nodemailer Module.
  2. Create Nodemailer transporter using SMTP.
  3. Setting up the smtpOptions object.
  4. Setting up mail options (mailOptions object).
  5. Deliver the mailOptions using the sendMail() method.
  6. Test emails using Mailtrap.
  7. Test emails using Ethereal.
  8. Sending emails using a Gmail account.

Related Articles:

Step1: Install Nodemailer Module

To get started with Nodemailer, you need Node.js version 6.0 or higher. All public Nodemailer functions support callbacks and Promises but if you wish to use async..await with Nodemailer, you will need at least Node v8.0.0.
You should also download and install it using yarn or npm:

 yarn add nodemailer
 >npm install --save nodemailer

The next step is to include the module in our application by adding the following line of code:

  const nodemailer = require('nodemailer');

Now we are ready to use Nodemailer. We will create the transporter in the following sections and configure the mail message.

Step2: Create Nodemailer transporter using  SMTP 

SMTP is the most common transport mechanism in Nodemailer. It is a protocol that connects various email hosts because everything is relatively essential with SMTP, all you have to do is set the host, port, authentication information, and method, and you are done. One of the advantages of using SMTP is that if you need to replace one provider with another, you only need to change the configuration options mentioned previously.

You must first set up a transport mechanism before sending any emails. This may be accomplished using a nodemailer. createTransport(type, options), where type is the transport mechanism (in our case SMTP) and options define the connection data and how it will be used.

 
 const  transport = nodemailer.createTransport("SMTP", {smtpOptions});

To create the reusable transporter object using the default SMTP transport, you can use:

 
 const  transport = nodemailer.createTransport({smtpOptions});

It is also good to double-check that the SMTP connection is working correctly. You can use the verify(callback) method to validate the connection and authentication.

   transporter.verify(function(error, success) {
   if (error) {
        console.log(error);
   } else {
        console.log('Server is ready');
   }
});

Remember that this callback simply checks for connection and authentication; it does not determine whether or not the service permits you to use a specific envelope From the address.

Step3: Setting up the smtpOptions

smtpOptions is an object that contains all the data related to the connection and the security parameters. The SMTP options can be divided into seven categories:

CategoriesThe smtp options
1. General optionsservice: this option is optional to identify well-known service identifiers such as “Gmail”, “Hotmail”…
port: is the port of the SMTP server to connect to. 
By default: 
587 : if secure is false or
465: if secure if true.
host: this option represents the hostname of the SMTP server or IP address to connect to. The default value is ‘localhost’. Note that we do not need this option with service; it is detected automatically.
auth: defines authentication type and provides the authentication options object. 
The authentication type by default is ‘login’ with the options object:{
user is the username
pass is the password for the user
 }
‘oauth2’ is an other option for authentication. You can use this type with the following options objects:
{XOAuth2: {xoauth2_options}}
{XOAuthToken: “base64data”}


authMethod: defines preferred authentication method, defaults to ‘PLAIN’.
2. TLS optionssecure: the value of this option by default is false, and that means TLS is used only if the server supports the STARTTLS extension. 
If true, the connection will use TLS when connecting to the server. 
In general, set this value to:
– true with the port 465. 
-false with port 587 or 25.
ignoreTLS: this option is used to ignore server support for STARTTLS, which means if this is true and secure is false, then TLS is not used even if the server supports STARTTLS extension.


requireTLS: if this is true and secure is false, then Nodemailer tries to use STARTTLS even if the server does not advertise support for it. If the connection can not be encrypted, the message is not sent.
3. Connection optionsname: this option is optional and contains the hostname of the client-server (defaults to machine name).
localAddress: is the local interface to bind to for network connections.
connectionTimeout: how many milliseconds to wait for the connection to establish (default is 2 minutes).
greetingTimeout: how many milliseconds to wait for the greeting after the connection is established (default is 30 seconds).
socketTimeout: how many milliseconds of inactivity to allow (default is 10 minutes).
4. Debug optionsdebug: if set to true, then logs SMTP traffic and outputs client and server messages to console. Otherwise, it logs only transaction events.
5. Security optionsdisableFileAccess: set this option to true if you do not want to allow files as content, so if an attachment or message node tries to fetch something from a file, the sending returns an error.
disableUrlAccess: set this option to true if you do not allow the use of URLs as content.
6. Pooling optionsWe set up the Pooling options when a pooled connection is used:


pool: we set this option to true to use pooled connections instead of creating a new connection for every email. The default value is false.
maxConnections: represent the maximum number of simultaneous connections to make against the SMTP server. It is set to 5 by default.
maxMessages: limits the number of messages sent through a single connection (defaults to 100). After maxMessages is reached, the connection is dropped, and a new one is created for the following messages
7. Proxy optionsproxy: this option enables proxying by adding a proxy URL. 
For example, HTTP proxy support:
proxy: ‘http://proxy-host:1234’

Example of smtpOptions:

The following example is the smtpOptions that we used in our forgot/reset password tutorial to send a forgot password message to the user. You can check this article here: Add Forgot/Reset Password to Login-Authentication System.

Furthermore, there is a complete example of how to send email using a Gmail account here: Nodemailer + Gmail: How to Send Emails from Node.js API using Gmail.

The authentication type used in the following example is ‘login’ for an ethereal account and the options object:{

user is the username

pass is the password for the user

 }

 const transporter = nodemailer.createTransport({
            host: 'smtp.ethereal.email',
            port: 587,
            auth: {
              user: process.env.USER, 
              pass: process.env.PASS 
            }
    })

Step4: Setting up mail options (mailOptions object)

The mailOptions object is used to precisely define who sends what to whom, and The following table resumes all the fields in five categories. We are not supposed to use all these options while sending a message; most the developers use only a few from the basic fields.

CategoriesmailOptions Fields
1. basic optionsfrom: The sender’s address. Example: ‘[email protected].
to: The email receiver or a list of receivers.
cc: Comma separated list or an array of recipients’ email addresses that will appear on the Cc: field
bcc: Comma separated list or an array of recipients’ email addresses that will appear on the Bcc: field
subject: The email Subject line.
text: contain the plain-text body.
html: contain The HTML body of the message.
attachments: this field is used to add different types of data to your message such as files and embedding images.
2. Routing optionssender: The email address of the Sender field. This field is optional and from is enough.
replyTo: The email address that will appear on the Reply-To field.
inReplyTo: The message-ID this message is replying to.
references: contains the message-ID list.
envelope: optional SMTP envelope.
3. Content optionsattachDataUrls: if this field is set to true, then convert all the data: images in the HTML content of this message to embedded attachments.
watchHtml: this field was used for specific Apple Watch HTML version of the message. Note that the latest watches have no problems rendering text/html content, so watchHtml.
amp: AMP4EMAIL specific HTML version of the message. When using this option, ensure it is a complete and valid AMP4EMAIL document. Otherwise the amp will be ignored.
icalEvent: iCalendar event to use as an alternative. 
alternatives: this option is used to insert alternative contents of the main body in addition to text and htlm.
encoding: identifies encoding for text/html strings (defaults to ‘utf-8’, other values are ‘hex’ and ‘base64’)
raw: existing MIME message to use instead of generating a new one. 
textEncoding: force content-transfer-encoding for text values. By default, the best option is detected.
4. Header optionspriority: this option is for Setting the message importance headers. It can be ‘high’‘normal’ or ‘low’. The default value is normal.
headers: contains an object or array of additional header fields.
messageId: The Message-Id is optional. A random value will be generated if not set.
date: optional Date value, current UTC string will be used if not set.
5. Security optionsdisableFileAccess: Set this option to true if you do not allow using files as content. When this field is set in the transport options, the value in mail options is ignored.
disableUrlAccess: you can set this option to true if you do not allow using Urls as content. When this field is set in the transport options, the value in mail options is ignored.

Example of mailOptions:

The following example is the mailOptions that we used in our forgot/reset password tutorial to send forgot password message to the user. You can check this article here: Add Forgot/Reset Password to Login-Authentication System.

  
 let  message = `<p>Please use the below token to reset your password with the <code>/apiRouter/reset-password</code> api route:</p>
                       <p><code>${resetToken}</code></p>`; // Here you can replace the message with your HTML code.

  const  mailOptions = {
    from: process.env.EMAIL_FROM,
    to: email, // the user email
    subject: ' Reset your Password',
    html: `<h4>Reset Password</h4>
                   ${message}`
   };



Step5: Deliver the mailOptions using the sendMail()

In the sections above, we created a reusable Nodemailer transporter using the SMTP transport mechanism, and we set up the mailOptions object. In this section, we will send the message object using the sendMailer() method of the defined SMTP transporter.

Example of using sendMail() :

 const  info = transport.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log("Message sent: %s", info.messageId);
});

Nodemailer Example:

  const nodemailer = require('nodemailer');

  const transporter = nodemailer.createTransport({
            host: 'smtp.ethereal.email',
            port: 587,
            auth: {
              user: process.env.USER, 
              pass: process.env.PASS 
            }
    })


   let  message = `<p>Please use the below token to reset your password with the <code>/apiRouter/reset-password</code> api route:</p>
                       <p><code>${resetToken}</code></p>`; // Here you can replace the message with your HTML code.

  const  mailOptions = {
    from: process.env.EMAIL_FROM,
    to: email, // the user email
    subject: ' Reset your Password',
    html: `<h4>Reset Password</h4>
                   ${message}`
   };



   const  info = transport.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log("Message sent: %s", info.messageId);
});




   


Test emails in nodemailer using Mailtrap

Mailtrap is an online tool for email testing in a dev environment. It captures SMTP traffic and messages, analyses the content of the emails for spam score, validates HTML/CSS, and then displays how they should look in a real email.

In order to use Mailtrap, we need first to set up an account. You can set up your account for free here: Mailtrap Sign Up.

Then click on My inbox, and then select the SMTP settings tab. Next, click on Integrations and select the Nodemailer integration. Please copy the code and insert it into your application.

The code already contains a transporter and the smtpOptions:

 var transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "11ff58c26075fa",
    pass: "1d4f72f480930e"
  }
});

If you want to see a complete example of how to send and test reset password email using nodemailer, check this article: …………..

  
const nodemailer = require('nodemailer');

  const  transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "11ff58c26075fa",
    pass: "1d4f72f480930e"
  }
});


   let  message = `<p>Please use the below token to reset your password with the <code>/apiRouter/reset-password</code> api route:</p>
                       <p><code>${resetToken}</code></p>`; // Here you can replace the message with your HTML code.

  const  mailOptions = {
    from: process.env.EMAIL_FROM,
    to: email, // the user email
    subject: ' Reset your Password',
    html: `<h4>Reset Password</h4>
                   ${message}`
   };



   const  info = transport.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log("Message sent: %s", info.messageId);
});




  

Test emails in nodemailer using Ethereal

Ethereal is a fake SMTP service used to auto-generate email test accounts.

You can generate an email account from Nodemailer using the following line of code:

 
 let testAccount = await nodemailer.createTestAccount();

Or create an account here: create Ethereal account.

Ethereal account:

..

To send an email using that account, all you have to do is copy the code in the Nodemailer configuration section and insert it into your application.
If you want to check your mailbox, click on Open Mailbox.
If you want to see a complete example of how to send and test reset password email using nodemailer, check this article: …………..

  const transporter = nodemailer.createTransport({
    host: 'smtp.ethereal.email',
    port: 587,
    auth: {
        user: '[email protected]',
        pass: 'E8QVyfKbNut785cMKY'
    }
});


  
const nodemailer = require('nodemailer');

  const transporter = nodemailer.createTransport({
    host: 'smtp.ethereal.email',
    port: 587,
    auth: {
        user: '[email protected]',
        pass: 'E8QVyfKbNut785cMKY'
    }
});


   let  message = `<p>Please use the below token to reset your password with the <code>/apiRouter/reset-password</code> api route:</p>
                       <p><code>${resetToken}</code></p>`; // Here you can replace the message with your HTML code.

  const  mailOptions = {
    from: process.env.EMAIL_FROM,
    to: email, // the user email
    subject: ' Reset your Password',
    html: `<h4>Reset Password</h4>
                   ${message}`
   };



   const  info = transport.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log("Message sent: %s", info.messageId);
});




  

Conclusion

In this article, we explained and demonstrated how to create and send emails from a node.js API using Nodemailer via an SMTP service, and we gave two ways to test emails: Mailtrap and Ethereal. Hope this was helpful.

You might also like:

Best practices for optimizing MySQL database performance.

Node.js + MySQL : Add Forgot/Reset Password to Login-Authentication System.

How to add Custom Error Handler Middleware to your Node.js/Express API.

Nodemailer + Gmail: How to Send Emails from Node.js API using Gmail.

Complete JWT Authentication and Authorization System for MySQL/Node.js API.

How to Build a Complete API for User Login and Authentication using MySQL and Node.js.

How to store Session in MySQL Database using express-mysql-session.

How to interact with MySQL database using async/await promises in node.js ?

How to use Sequelize async/await to interact with MySQL database in Node.js.

MANY-TO-MANY Association in MYSQL Database using Sequelize async/await with Node.js.

ONE-TO-ONE Association in MYSQL Database using Sequelize async/await with Node.js

ONE-TO-ONE Association in MYSQL Database using Sequelize async/await with Node.js.

How to add Routes to insert data into MySQL database-related tables in Node.js API?

Example How to use initialize() Function in Node.js/Express API .

Why is Connection Pooling better than Single Connection?.

How to create MySQL database using node.js.

Leave a Comment

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

Translate »