4 Methods to Send Emails Using Node.js (w/ Codes - Nodemailer Module, Gmail API, Postmark API & SuprSend)

Nik L. - Jan 16 - - Dev Community

Some of our articles:

  1. Building a Scalable Notification System with gRPC and Microservices
  2. How to Send Email Notifications using Python? (With Code Examples)
  3. A Complete Guide on Notification Infrastructure for Modern Applications in 2023

Method 1: Using the Nodemailer Module

1.1 Installation and Setup



npm install nodemailer --save


Enter fullscreen mode Exit fullscreen mode

Create emailSender.js:



const nodemailer = require('nodemailer');

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

// ... rest of the code


Enter fullscreen mode Exit fullscreen mode

1.2 Creating a Nodemailer Transporter



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


Enter fullscreen mode Exit fullscreen mode

1.3 Setting Message Options



const mailOptions = {
  to: 'test@example.com',
  from: 'your-email@gmail.com',
  subject: 'Subject',
  text: 'Body'
};


Enter fullscreen mode Exit fullscreen mode

1.4 Sending Emails with Attachments



const mailOptionsWithAttachment = {
  // ... other options
  attachments: [
    {
      filename: 'file.txt',
      path: '/path/to/file.txt'
    }
  ]
};


Enter fullscreen mode Exit fullscreen mode

1.5 HTML Emails with Dynamic Content

Install email-templates and pug:



npm install email-templates pug --save


Enter fullscreen mode Exit fullscreen mode

Update emailSender.js as per your template.

1.6 Now, create your email templates.

Let's focus on a common scenario: sending a welcome email for new user registration.

Create subject.pug:



= `Hi #{firstName} #{lastName}, welcome to My App!`


Enter fullscreen mode Exit fullscreen mode

Create html.pug:



h1 Hello #{firstName} #{lastName}
p.
  Welcome to My App! Now your test emails will be safe.
  We just need to make sure your account is real.
a(href='https://example.com/confirmation') Confirm!


Enter fullscreen mode Exit fullscreen mode

Ensure your directory structure looks like this:



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


Enter fullscreen mode Exit fullscreen mode

1.7 Sending Emails with Dynamic Content

Now, let's modify our Node.js application to use these templates:



// ... (previous code)

// Step 5: Create an email-templates instance
const Email = require('email-templates');
const email = new Email({
  message: {
    from: 'hi@example.com',
  },
  send: true,
  transport: {
    host: 'smtp.mailtrap.io',
    port: 2525,
    ssl: false,
    tls: true,
    auth: {
      user: 'your-mailtrap-username',
      pass: 'your-mailtrap-password',
    },
  },
});

// Step 6: Define user data
const people = [
  { firstName: 'Diana', lastName: 'One', email: 'diana@example.com' },
  { firstName: 'Alex', lastName: 'Another', email: 'alex@example.com' },
];

// Step 7: Send emails for each user
people.forEach((person) => {
  email
    .send({
      template: 'welcome',
      message: {
        to: person.email,
      },
      locals: person,
    })
    .then(console.log)
    .catch(console.error);
});


Enter fullscreen mode Exit fullscreen mode

Replace placeholder values in the code with your actual credentials.

Method 2: Sending Emails with Gmail SMTP

2.1 Gmail SMTP Configuration



npm install nodemailer --save


Enter fullscreen mode Exit fullscreen mode

Create gmailSender.js:



const nodemailer = require('nodemailer');

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

// ... rest of the code


Enter fullscreen mode Exit fullscreen mode

2.2 App Password for Enhanced Security

Follow the steps for generating an App Password.

2.3 Sending an Email with Gmail SMTP

Update gmailSender.js:



const mailOptions = {
  to: 'test@example.com',
  from: 'your-email@gmail.com',
  subject: 'Subject',
  text: 'Body'
};


Enter fullscreen mode Exit fullscreen mode

2.4 Advanced Usage: oAuth2 Authentication

Include oAuth2 authentication in gmailSender.js:



// oAuth2 authentication
const oauth2Client = new OAuth2(
  'YOUR_CLIENT_ID',
  'YOUR_CLIENT_SECRET',
  'YOUR_REDIRECT_URL'
);

// ... rest of the code


Enter fullscreen mode Exit fullscreen mode

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

Step 1: Sign Up for Postmark and Create API Token

  1. Sign up for Postmark.
  2. Create an API token in your Postmark account.

Step 2: Install the Postmark JavaScript Client



npm install --save postmark


Enter fullscreen mode Exit fullscreen mode

Step 3: Create postmark.js

Create a file named postmark.js:



const postmark = require('postmark');

const client = new postmark.ServerClient('YOUR_POSTMARK_API_TOKEN');

const message = {
  From: 'your-email@example.com',
  To: 'recipient@example.com',
  Subject: 'Subject of the Email',
  TextBody: 'Text content of the email',
  HtmlBody: '<strong>HTML content of the email</strong>',
};

client
  .sendEmail(message)
  .then((response) => {
    console.log('Email sent\n', response);
  })
  .catch((error) => {
    console.error(error);
  });


Enter fullscreen mode Exit fullscreen mode

Step 4: Update postmark.js

Replace 'YOUR_POSTMARK_API_TOKEN' with the API token you obtained from your Postmark account.


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

Step I: Log in to the SuprSend Account

Visit the SuprSend login page and enter your Email Address and Password. Try SuprSend for free.

Image description

Step II: Integrate with Email(s)

Install SuprSend using npm or yarn.

Image description

Step III: Create & Load Template

Create templates using the drag & drop editor.

Image description

Step IV: Create Smart Flow (Routing)

Define rules and logic for notification flows.

Image description

Step V: Trigger a Notification Event via API

Integrate the SuprSend API into your Node application.




        npm install @suprsend/node-sdk

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



Enter fullscreen mode Exit fullscreen mode

Installation




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

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



Enter fullscreen mode Exit fullscreen mode

Step VI: Check Event Analytics And Logs

View granular channel-wise and vendor-wise analytics through the unified dashboard. Explore more about logs.

Image description


You may want to check out other SuprSend SDKs too. Consider giving us a star after usage. It's free and open.

GitHub logo suprsend / suprsend-go

SuprSend SDK for go

suprsend-go

SuprSend Go SDK

Installation

go get github.com/suprsend/suprsend-go
Enter fullscreen mode Exit fullscreen mode

Usage

Initialize the SuprSend SDK

import (
    "log"

    suprsend "github.com/suprsend/suprsend-go"
)

func main() {
    opts := []suprsend.ClientOption{
        // suprsend.WithDebug(true),
    }
    suprClient, err := suprsend.NewClient("__api_key__", "__api_secret__", opts...)
    if err != nil {
        log.Println(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Trigger Workflow

package main
import (
    "log"

    suprsend "github.com/suprsend/suprsend-go"
)

func main() {
    // Instantiate Client
    suprClient, err := suprsend.NewClient("__api_key__", "__api_secret__")
    if err != nil {
        log.Println(err)
        return
    }
    // Create WorkflowTriggerRequest body
    wfReqBody := map[string]interface{}{
        "workflow": "workflow-slug",
        "recipients": []map[string]interface{}{
            {
                "distinct_id": "0f988f74-6982-41c5-8752-facb6911fb08",
                // if $channels is present, communication will be tried on mentioned channels only (for this request).
                // "$channels": []string{"email"},
Enter fullscreen mode Exit fullscreen mode

GitHub logo suprsend / suprsend-py-sdk

SuprSend SDK for python3

suprsend-py-sdk

This package can be included in a python3 project to easily integrate with SuprSend platform.

Installation

suprsend-py-sdk is available on PyPI. You can install using pip.

pip install suprsend-py-sdk
Enter fullscreen mode Exit fullscreen mode

This SDK depends on a system package called libmagic. You can install it as follows:

# On debian based systems
sudo apt install libmagic

# If you are using macOS
brew install libmagic
Enter fullscreen mode Exit fullscreen mode

Usage

Initialize the SuprSend SDK

from suprsend import Suprsend
# Initialize SDK
supr_client = Suprsend("workspace_key", "workspace_secret")
Enter fullscreen mode Exit fullscreen mode

Following example shows a sample request for triggering a workflow. It triggers a pre-created workflow purchase-made to a recipient with id: distinct_id, email: user@example.com & androidpush(fcm-token): __android_push_fcm_token__

from suprsend import WorkflowTriggerRequest
# Prepare Workflow body
wf = WorkflowTriggerRequest(
  body={
    "workflow": "purchase-made"
    "recipients": [
        {
          "distinct_id": "0f988f74-6982-41c5-8752-facb6911fb08",
          # if $channels is present, communication will be tried on mentioned
Enter fullscreen mode Exit fullscreen mode

GitHub logo suprsend / suprsend-node-sdk

Official SuprSend SDK for Node.js

suprsend-node-sdk

This package can be included in a node project to easily integrate with SuprSend platform.

Installation

npm install @suprsend/node-sdk@latest
Enter fullscreen mode Exit fullscreen mode

Initialization

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

const supr_client = new Suprsend("workspace_key", "workspace_secret");
Enter fullscreen mode Exit fullscreen mode

It is a unified API to trigger workflow and doesn't require user creation before hand. If you are using our frontend SDK's to configure notifications and passing events and user properties from third-party data platforms like Segment, then event-based trigger would be a better choice.

const { Suprsend, WorkflowTriggerRequest } = require("@suprsend/node-sdk");
const supr_client = new Suprsend("workspace_key", "workspace_secret");

// workflow payload
const body = {
  workflow: "_workflow_slug_",
  actor: {
    distinct_id: "0fxxx8f74-xxxx-41c5-8752-xxxcb6911fb08",
    name: "actor_1",
  },
  recipients: [
    {
      distinct_id: "0gxxx9f14-xxxx-23c5-1902-xxxcb6912ab09",
      $email: ["abc@example.com"
Enter fullscreen mode Exit fullscreen mode

GitHub logo suprsend / suprsend-react-inbox

SuprSend SDK for integrating inbox functionality in React applications

@suprsend/react-inbox

Integrating SuprSend Inbox channel in React websites can be done in two ways:

  • SuprSendInbox component which comes with UI and customizing props.
  • SuprSendProvider headless component and hooks, incase you want to totally take control of UI. (example: Full page notifications).

Detailed documentation can be found here: https://docs.suprsend.com/docs/inbox-react

Installation

You can install SuprSend inbox SDK using npm/yarn

npm install @suprsend/react-inbox
Enter fullscreen mode Exit fullscreen mode

SuprSendInbox Integration

After installing, Import the component in your code and use it as given below. Replace the variables with actual values.

import SuprSendInbox from '@suprsend/react-inbox'
import 'react-toastify/dist/ReactToastify.css' // needed for toast notifications, can be ignored if hideToast=true

// add to your react component;
<SuprSendInbox
  workspaceKey='<workspace_key>'
  subscriberId='<subscriber_id>'
  distinctId='<distinct_id>'
/>
Enter fullscreen mode Exit fullscreen mode
interface ISuprSendInbox {
  workspaceKey: string
  distinctId: string | null
  subscriberId: string | null
  tenantId?: string
  stores?: IStore[]
  pageSize?: number
  pagination?: boolean
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . .