DEV Community

Cover image for Building a Secure API for sending the Emails
Yashraj
Yashraj

Posted on • Edited on

Building a Secure API for sending the Emails

Email notifications are crucial for modern web applications. In this guide, we'll build a secure email notification service using Express.js and Gmail's OAuth2 authentication. Our service will accept webhook requests and automatically send emails based on the incoming data.

What We're Building

We'll create an Express server that:

  • Receives webhook data via POST requests
  • Authenticates with Gmail using OAuth2
  • Sends customized emails based on the webhook payload
  • Handles errors gracefully

Prerequisites

  • Node.js installed on your machine
  • A Google Cloud Console project with Gmail API enabled
  • OAuth2 credentials (Client ID, Client Secret, Refresh Token)
  • Basic understanding of Express.js and async/await

Project Setup

First, install the required packages:

npm install express body-parser nodemailer googleapis dotenv
Enter fullscreen mode Exit fullscreen mode

Create a .env file with your credentials:

CLIENT_ID=your_client_id
CLIENT_SECRET=your_client_secret
REDIRECT_URI=your_redirect_uri
REFRESH_TOKEN=your_refresh_token
EMAIL_USER=your_email@gmail.com
Enter fullscreen mode Exit fullscreen mode

If you encounter any difficulties setting up these credentials, like I did, you can follow the steps below...

Step-1: Create a new Google Cloud project:

a. Go to https://console.cloud.google.com/
b. Click on the project dropdown at the top of the page
c. Click "New Project"
d. Enter a project name and click "Create"

Create a new Google Cloud Project

Step-2: Enable the Gmail API:
a. In the left sidebar, go to "APIs & Services" > "Library"
b. Search for "Gmail API"
c. Click on "Gmail API" and then click "Enable"

Enable Gmail API


Step-3: Configure the OAuth consent screen:
a. Go to "APIs & Services" > "OAuth consent screen"
b. Choose "External" as the user type and click "Create"
c. Fill in the required fields:
- App name: [Your app name]
- User support email: [Your email]
- Developer contact information: [Your email]
d. Click "Save and Continue"
e. On the "Scopes" page, click "Add or Remove Scopes"
f. Find and select "https://mail.google.com/" scope
g. Click "Update" and then "Save and Continue"
h. On the "Test users" page, click "Add Users"
i. Add your Gmail address and click "Save and Continue"
j. Review the summary and click "Back to Dashboard"


Step-4: Create OAuth2 credentials:
a. Go to "APIs & Services" > "Credentials"
b. Click "Create Credentials" > "OAuth client ID"
c. Choose "Web application" as the application type
d. Name: [Your app name]
e. Authorized JavaScript origins: Add your server's domain (e.g., http://localhost:3000 for local development)
How to setup google auth02
f. Authorized redirect URIs:
- Add: https://developers.google.com/oauthplayground
- Add your server's callback URL if you have one (e.g., http://localhost:3000/auth/google/callback)
g. Click "Create"
h. A popup will show your Client ID and Client Secret. Save these securely.


Step-5: Get a new Refresh Token:
a. Go to https://developers.google.com/oauthplayground/

Refresh Token

b. Click the gear icon(Like Settings) in the top right corner
c. Click on check box "Use your own OAuth credentials"
d. Enter your new Client ID and Client Secret
e. Close the settings
f. In the left sidebar, find "Gmail API v1"
g. Select https://mail.google.com/
h. Click "Authorize APIs"
i. Choose your Google account and grant the requested permissions
j. On the next screen, click "Exchange authorization code for tokens"
k. Copy the "Refresh token" from the response

If you encounter any issues during this process or when testing the email functionality, please provide the specific error messages or behavior you're seeing in comments.


The Code Explained

Let's break down the implementation step by step:

1. Initial Setup and Dependencies

const express = require("express");
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");
const { google } = require("googleapis");
require("dotenv").config();

const app = express();
app.use(bodyParser.json());
Enter fullscreen mode Exit fullscreen mode

This section sets up our Express server and imports necessary dependencies. We use body-parser to parse JSON requests and dotenv to manage environment variables.

2. OAuth2 Configuration

const oAuth2Client = new google.auth.OAuth2(
  CLIENT_ID,
  CLIENT_SECRET,
  REDIRECT_URI
);
oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });
Enter fullscreen mode Exit fullscreen mode

We create an OAuth2 client using Google's authentication library. This handles token refresh and authentication with Gmail's API.

3. Email Sending Function

async function sendEmail(webhookData) {
  const {
    receiver_email, //change data based on your needs
  } = webhookData;

  try {
    const accessToken = await oAuth2Client.getAccessToken();
    const transport = nodemailer.createTransport({
      service: "gmail",
      auth: {
        type: "OAuth2",
        user: process.env.EMAIL_USER,
        clientId: CLIENT_ID,
        clientSecret: CLIENT_SECRET,
        refreshToken: REFRESH_TOKEN,
        accessToken: accessToken,
      },
    });

    const mailOptions = {
      from: `Your Name <${process.env.EMAIL_USER}>`,
      to: receiver_email,
      subject: ``, //Add Subject of Email
      html: ``, // Add your HTML template here
    };

    return await transport.sendMail(mailOptions);
  } catch (error) {
    console.error("Error in sendMail function:", error);
    throw error;
  }
}
Enter fullscreen mode Exit fullscreen mode

This function:

  • Extracts data from the webhook payload, you can modify payload based on needs
  • Gets a fresh access token
  • Creates a transport with OAuth2 authentication
  • Sends the email with customized content

4. Webhook Endpoint

app.post("/webhook", async (req, res) => {
  try {
    const webhookData = req.body;
    await sendEmail(webhookData);
    res.status(200).send("Email sent successfully");
  } catch (error) {
    console.error("Error processing webhook:", error);
    res.status(500).send("Error processing webhook");
  }
});
Enter fullscreen mode Exit fullscreen mode

Our webhook endpoint:

  • Receives POST requests
  • Processes the webhook data
  • Sends emails
  • Returns appropriate responses

Testing

Test your webhook using curl or Postman:

curl -X POST http://localhost:4000/webhook \
-H "Content-Type: application/json" \
-d '{
  "receiver_email": "test@example.com",
}'
Enter fullscreen mode Exit fullscreen mode

Troubleshooting

Common issues and solutions:

  1. Authentication Errors: Check your OAuth2 credentials
  2. Token Expiration: Ensure refresh token is valid
  3. Missing Data: Validate webhook payload

Conclusion

You now have a secure, OAuth2-authenticated email notification system! This implementation provides a solid foundation for building more complex notification systems while maintaining security and reliability.

Hope this post is useful for you to setting up email service.

Happy coding! 🚀

Top comments (0)