Email management

How to Send Transactional Emails Using Node.js? (4 Methods With Codes - Nodemailer Module, Gmail API, Sendgrid API & SuprSend)

Sanjeev Kumar
January 16, 2024
Learn to send transactional emails in Node.js using Nodemailer, Gmail API, SendGrid API, and SuprSend. Step-by-step guides and code examples included.
TABLE OF CONTENTS

In the realm of large-scale customer-centric applications, the importance of sending emails cannot be overstated. It serves as a vital, cost-effective, and user-friendly communication tool, especially for notifying users about crucial application events like account activation, password changes, and user verification. Node.js, a perennial favorite among programming languages, continues to be a top choice for enterprises tackling challenges in building resilient applications. This article explores four distinct methods for sending transactional emails using Node.js, shedding light on the pros and cons of each approach.

Method 1: Using the Nodemailer Module

1.1 Installation and Setup

Before diving into the Nodemailer magic, let's kick things off by installing the module. Open your terminal and run the following command:

Code Container Example
   
      npm install nodemailer --save
        
        


Or if you prefer Yarn:

   
      yarn add nodemailer
        
        


Once installed, let's set up Nodemailer in your Node.js application. Create a file, let's call it emailSender.js:

   
      // emailSender.js
      const nodemailer = require('nodemailer');

      // Step 2: Create a Nodemailer transporter
      const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: 'your-email@gmail.com',
          pass: 'your-email-password',
        },
      });

      // Step 3: Set Nodemailer message options
      const mailOptions = {
        from: 'your-email@gmail.com',
        to: 'recipient@example.com',
        subject: 'Hello from Nodemailer',
        text: 'This is a test email from Nodemailer!',
      };

      // Step 4: Deliver a message with sendMail()
      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          console.error('Error:', error.message);
        } else {
          console.log('Email sent:', info.response);
        }
      });    
        
        


1.2 Creating a Nodemailer Transporter

The createTransport function in Nodemailer configures the email transport method. Here, we use Gmail as our SMTP service. Replace 'your-email@gmail.com' and 'your-email-password' with your Gmail credentials.

1.3 Setting Message Options

The mailOptions object defines essential email parameters such as sender, recipient, subject, and text body. Customize it based on your needs.

1.4 Sending Emails with Attachments

Nodemailer makes it easy to attach files to emails. Let's enhance our example to send an email with an attachment:

   
      // ... (previous code)

      // Attachments
      const attachments = [
        {
          filename: 'document.pdf',
          path: '/path/to/document.pdf',
        },
        {
          filename: 'image.png',
          path: '/path/to/image.png',
          cid: 'unique-image-id',
        },
      ];

      // Update mailOptions with attachments
      const mailOptionsWithAttachments = { ...mailOptions, attachments };

      // Send email with attachments
      transporter.sendMail(mailOptionsWithAttachments, (error, info) => {
        // ... (error handling and logging)
      });
        
        


1.5 HTML Emails with Dynamic Content

Sending HTML emails with dynamic content is a breeze with Nodemailer and the email-templates package. Install it using:

   
      npm install email-templates pug --save
        
        


Or with Yarn:

   
      yarn add email-templates pug
        
        


Create a folder named templates with subject.pug and html.pug files inside. Let's update our emailSender.js:

   
      // ... (previous code)

      const Email = require('email-templates');

      const email = new Email({
        message: {
          from: 'your-email@gmail.com',
        },
        send: true,
        transport: transporter, // Use the existing transporter
      });

      const person = {
        firstName: 'John',
        lastName: 'Doe',
      };

      // Send HTML email with dynamic content
      email
        .send({
          template: 'welcome',
          message: {
            to: 'recipient@example.com',
          },
          locals: person,
        })
        .then(console.log)
        .catch(console.error);
        
        

Ensure that your directory structure looks like this:

├── app.js
├── emails
│   └── welcome
│       ├── html.pug
│       └── subject.pug


In the next response, we'll cover Section 2: Sending Emails with Gmail, including Gmail SMTP configuration and authentication methods.

Method 2: Sending Emails with Gmail SMTP

2.1 Gmail SMTP Configuration

Now, let's explore sending emails using Gmail SMTP, a secure and reliable method.

Firstly, install Nodemailer if you haven't already, using above shared method in 1.1:

In your Node.js application, create a file, let's call it gmailSender.js:

   
      // emailSender.js
      const nodemailer = require('nodemailer');

      // Step 2: Create a Nodemailer transporter
      const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: 'your-email@gmail.com',
          pass: 'your-email-password',
        },
      });

      // Step 3: Set Nodemailer message options
      const mailOptions = {
        from: 'your-email@gmail.com',
        to: 'recipient@example.com',
        subject: 'Hello from Nodemailer',
        text: 'This is a test email from Nodemailer!',
      };

      // Step 4: Deliver a message with sendMail()
      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          console.error('Error:', error.message);
        } else {
          console.log('Email sent:', info.response);
        }
      });
        
        


2.2 App Password for Enhanced Security

To authenticate with Gmail SMTP securely, it's recommended to use an App Password. Follow these steps:

  1. Go to your Google Account Security.
  2. Under "Signing in to Google," enable "2-Step Verification" if not enabled.
  3. In the "Signing in to Google" section, click on "App Passwords."
  4. Select "Mail" in the "Select app" dropdown and "Other (Custom name)" in the "Select device" dropdown.
  5. Click "Generate."
  6. Copy the generated password and use it in the gmailSender.js file.

2.3 Sending an Email with Gmail SMTP

Now, let's modify our gmailSender.js file to send a test email:

   
      // ... (previous code)

      // Step 3: Set Gmail SMTP message options
      const mailOptions = {
        from: 'your-email@gmail.com',
        to: 'recipient@example.com',
        subject: 'Hello from Gmail SMTP',
        text: 'This is a test email from Gmail SMTP!',
      };

      // Step 4: Deliver a message with sendMail()
      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          console.error('Error:', error.message);
        } else {
          console.log('Email sent:', info.response);
        }
      });
        
        


2.4 Advanced Usage: oAuth2 Authentication

For enhanced security, consider using oAuth2 authentication. It involves obtaining an access token. Here's a basic example:

   
      // ... (previous code)

      // OAuth2 configuration
      const oAuth2Client = {
        clientId: 'your-client-id',
        clientSecret: 'your-client-secret',
        refreshToken: 'your-refresh-token',
        accessToken: 'your-access-token',
        expires: 12345, // Set the expiration time
      };

      // Update transporter configuration
      transporter.use('oauth2', oAuth2Client);
        
        


Method 3: Sending Emails using a Transactional Email API (e.g., SendGrid)

Step 1: Sign Up for SendGrid and Create API Key

  1. Sign up for SendGrid and create an API key with full access.
  2. Install the SendGrid JavaScript client with npm:
   
      npm install --save @sendgrid/mail
        
        


Step 2: Create a SendGrid API Key

   
      const sendgrid = require('@sendgrid/mail');
      const SENDGRID_API_KEY = "";
      sendgrid.setApiKey(SENDGRID_API_KEY);
        
        

Step 3: Send Email with SendGrid

   
      const msg = {
        to: 'recipient@example.com',
        from: 'your-email@example.com',
        subject: 'Sending with SendGrid Is Fun',
        text: 'and easy to do anywhere, even with Node.js',
        html: 'and easy to do anywhere, even with Node.js',
      };

      sendgrid.send(msg)
        .then((resp) => {
          console.log('Email sent\n', resp);
        })
        .catch((error) => {
          console.error(error);
        });
        
        

Method 4: Using SuprSend - Third-Party Multichannel Notification Infrastructure with Node SDK

A third-party multichannel notification infrastructure provider, such as SuprSend, presents an avenue for sending cross-channel notifications through a unified API, covering various channels like Emails, SMS, and Push Notifications. SuprSend streamlines the notification flow by managing all relevant channels and providers seamlessly through a single API, eliminating the need for extensive coding.

Key Features & Benefits:

  1. Extensive Integration Options: Seamless integration with 50+ Communication Service Providers (CSPs) and across 6+ communication channels, like Mixpanel, Segment, Twilio, Mailchimp, Slack, Teams, SNS, Vonage, Whatsapp and more.
  2. No Tech Dependency: End-to-end notification management without involving the engineering team, optimizing their productivity. Just integrate the Node SDK once, and your product team will manage everything else.
  3. Intelligent Routing: Create and implement intelligent cross-channel flows across providers without technical dependencies.
  4. In-App SDK: Provides a fully loaded, developer-ready in-app layer for both web and mobile applications.
  5. Granular Template Management: Utilize an intuitive drag & drop editor for designing templates, offering superior control over the content.
  6. Powerful Workspace: Efficiently manage various projects with distinct integrations, workflows, and templates in each workspace.
  7. Unified Analytics: Track, measure, and make data-driven decisions with a unified view of cross-channel analytics across vendors.
  8. Smart Automation: Automate synchronization, refreshing, and notification triggers, allowing more focus on critical tasks.
  9. Quick Scalability: SuprSend automates scalability, putting it on autopilot for a hassle-free experience.

Cons:

  1. Cost Considerations: Managing multiple notification channels may incur costs. Monthly Notification Limits:
  2. Be mindful of limitations on the maximum number of notifications receivable per month.

Designed with a "developer-first" approach, SuprSend handles the heavy lifting, enabling engineering teams to concentrate on their tasks without the added complexity of managing notifications.

Getting Started with SuprSend for Sending emails in Node:

Step I: Log in to the SuprSend Account.

Image description

Step II: Integrate with Email(s).

  • SuprSend provides a ready-to-integrate provider list for emails, including AWS SES, Mailchimp (Mandrill), Mailgun, Netcore, Outlook, Postmark, SendGrid, and more.
  • After logging in, navigate to the integration section, choose the desired email channel, and enter the necessary information.
Image description

Step III: Create & Load Template.

  • SuprSend allows you to create and store messaging content with a user-friendly drag & drop editor. To create a template, head to the "Templates" tab, click "Create," and then utilize the "Drag & Drop Editor" for customization.
Image description

Step IV: Create Smart Flow (Routing).

  • Define rules and logic effortlessly by heading to the "Workflows" tab. Choose "Single Channel" and create a flow by adding basic details and logic conditions.
  • Combine templates, providers, routes, and channels to fire notifications.
Image description

Step V: Trigger a Notification Event via API
Following this step, we'll integrate the SuprSend API into our Node application. Begin by updating the Maven pom.xml file with the provided dependency and execute mvn compile to download the necessary components. More info in documentation.

     
        npm install @suprsend/node-sdk

        # to upgrade to latest SDK version
        npm install @suprsend/node-sdk@latest
        
    


Installation using npm or yarn

       
          const {Suprsend} = require("@suprsend/node-sdk");

          // Initialize SDK
          const supr_client = new Suprsend("WORKSPACE KEY", "WORKSPACE SECRET");
                  
    


Step VI: Check Event Analytics And Logs.

  • Gain granular channel-wise and vendor-wise analytics through the unified dashboard. View "Event Analytics" for actionable insights and access detailed logs through the "Logs" tab. Explore more about logs.
Image description

By following the steps outlined in this article, you can seamlessly integrate email functionality into your Node projects, facilitating communication with users and enhancing the overall user experience.

Written by:
Sanjeev Kumar
Engineering, SuprSend
ABOUT THE AUTHOR

What’s a Rich Text element?

The rich text element allows you to create and format headings, paragraphs, blockquotes, images, and video all in one place instead of having to add and format them individually. Just double-click and easily create content.

Static and dynamic content editing

A rich text element can be used with static or dynamic content. For static content, just drop it into any page and begin editing. For dynamic content, add a rich text field to any collection and then connect a rich text element to that field in the settings panel. Voila!

How to customize formatting for each rich text

Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.

Implement a powerful stack for your notifications

By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.