Engineering

How to Send Transactional Email with AWS SES in Next.js with Code Example?

Anjali Arya
June 11, 2023
TABLE OF CONTENTS
Need an alternative method to send emails without the setup hassles? Alternative Method - Send Transactional Emails in Next.js Using Any Email Provider Without API Integrations

In modern web applications, programmatically sending emails plays a crucial role in enhancing user experience, facilitating communication, and driving business growth. As a CTO or technical decision-maker, understanding the importance of email functionality is essential for building robust and user-centric applications.

This technical guide aims to provide CTOs and technical decision-makers like you with a comprehensive understanding of implementing email sending in Next.js applications. It covers the necessary steps, best practices, and optimizations required to ensure seamless and reliable email functionality.

Setting Up Next.js

Before we delve into implementing email sending in Next.js, let's briefly discuss the setup process and familiarize ourselves with the Next.js project structure and foundational concepts.

Next.js is a powerful React framework that simplifies the development of server-rendered React applications. To set up a Next.js project, follow these steps:

1. Install Node.js: Ensure that Node.js is installed on your system. You can download and install the latest LTS version from the official Node.js website.

2. Create a New Next.js Project:
Open your terminal or command prompt and run the following command to create a new Next.js project:

    npx create-next-app my-next-project
Copied ✔


3. Explore the Project Structure:
Once the project is created, navigate into the project directory using the following command:

cd my-next-project
Copied ✔


Inside the project directory, you will find the following important files and folders:

  • `pages`: This folder contains the pages of your application. Each JavaScript file inside this folder represents a unique page.
  • `public`: Place static files (e.g., images, fonts) in this folder, which can be accessed directly from the client-side.
  • `styles`: This folder is used for storing global styles or CSS modules.

4. Start the Development Server: To start the Next.js development server, run the following command:

npm run dev
Copied ✔
This command will start the development server, and you can access your Next.js application at `http://localhost:3000`

Selecting an Email Service Provider (ESP)

In this tutorial, we will use AWS SES, a cloud-based email-sending service provided by Amazon Web Services. It offers high deliverability, scalability, and cost-effectiveness. AWS SES integrates well with other AWS services and provides a robust SDK for Next.js applications.

Installing Required Packages

To enable email sending functionality in your Next.js application using AWS SES as the Email Service Provider (ESP), you need to install the necessary packages. Follow the steps below to install the required packages:

1. Open your terminal or command prompt and navigate to your Next.js project directory.
2. Run the following command to install the required packages:

npm install nodemailer aws-sdk
Copied ✔

Configuring Email Provider Credentials

To send emails using AWS SES, you need to acquire the necessary credentials and configure them securely in your Next.js application. Follow these steps:

1. Sign up for an AWS account if you haven't already. Go to the AWS Management Console and create an IAM user with appropriate permissions for using AWS SES.

2.
Obtain the Access Key ID and Secret Access Key for your IAM user. These credentials will be used to authenticate your Next.js application with AWS SES.

3.
In your Next.js project, create a `.env` file in the root directory. Add the following lines to the file:

    
AWS_ACCESS_KEY_ID=your_access_key_id   
AWS_SECRET_ACCESS_KEY=your_secret_access_key
		
    
Copied ✔

Note: Make sure to add `.env` to your `.gitignore` file to prevent the credentials from being committed to version control.

4.
Install the `dotenv` package to load the environment variables from the `.env` file. Run the following command:

    
npm install dotenv
		
    
Copied ✔

Then, in your Next.js application's entry file (e.g., `pages/_app.js`), add the following line at the top to load the environment variables:

    
require('dotenv').config();
		
    
Copied ✔


With the AWS SES credentials properly configured, your Next.js application is now ready to send emails using AWS SES. In the upcoming sections, we will dive into developing a helper function for email sending and integrating it into your Next.js application.

Developing a Helper Function for Email Sending

In this section, we will focus on developing a reusable helper function for email sending in Next.js. This helper function will abstract away the email-sending logic, making it easier to send emails from different parts of your application.

Configuration Setup in Next.js for AWS SES

To configure AWS SES in your Next.js application, follow these steps:

1.
Install the AWS SDK package if you haven't already done so:

    
npm install aws-sdk
		
    
Copied ✔


2. In the file where you plan to use the email-sending functionality (e.g., `utils/email.js`), import the AWS SDK and create a new instance of the AWS SES service:

    

import AWS from 'aws-sdk';

 AWS.config.update({ 
 region: 'your_aws_region',  
 accessKeyId: process.env.AWS_ACCESS_KEY_ID, 
 secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, 
 });

 const ses = new AWS.SES({ apiVersion: 'latest' });
		
    
Copied ✔


Replace `'your_aws_region'` with the AWS region where your SES service is configured.

3. With the SES configuration in place, you can now proceed to create the helper function for sending emails.

Creating a Helper Function for Sending Emails using AWS SES

In the same file (`utils/email.js`), add the following code to create a helper function for sending emails using AWS SES:

    
    
export async function sendEmail({ to, from, subject, message }) {
  const params = {
    Source: from,
    Destination: { ToAddresses: [to] },
    Message: {
      Subject: { Data: subject },
      Body: { Text: { Data: message } },
    },
  };

  try {
    const result = await ses.sendEmail(params).promise();
    console.log('Email sent:', result.MessageId);
    return result.MessageId;
  } catch (error) {
    console.error('Error sending email:', error);
    throw error;
  }
}
		
    
Copied ✔

This helper function accepts an object with the `to`, `from`, `subject`, and `message` properties. It uses the `ses.sendEmail()` method to send the email using the configured AWS SES service.
To send an email from any part of your Next.js application, import the `sendEmail` function from `utils/email.js` and invoke it with the appropriate email details.

    
import { sendEmail } from '../utils/email.js';

// Example usage
try {
  await sendEmail({
    to: 'recipient@example.com',
    from: 'sender@example.com',
    subject: 'Hello from Next.js',
    message: 'This is a test email sent from Next.js using AWS SES.',
  });
} catch (error) {
  // Handle error
}
		
    
Copied ✔


By creating this helper function, you can easily integrate email sending functionality into various parts of your Next.js application. The AWS SES service handles the actual email delivery, ensuring reliable and scalable email sending capabilities.

Integrating the Helper Function into Next.js

Once you have developed the helper function for sending emails, the next step is to integrate it into your Next.js application. In this section, we will explore how to identify the areas in your application that require email functionality and integrate the helper function accordingly. Let's dive in!

Identifying Areas Requiring Email Functionality

Before integrating the helper function, identify the areas in your Next.js application where email functionality is required. These areas may include:

  • User registration: Sending a welcome email to new users upon successful registration.
  • Password reset: Sending an email with a password reset link to users who have forgotten their passwords.
  • Contact forms: Sending email notifications when users submit contact or inquiry forms.
  • Order confirmation: Sending order confirmation emails to customers after successful purchase.
  • Transactional emails: Sending email notifications for various events or actions within your application.

Integration of the Helper Function

To integrate the helper function into your Next.js application, follow these steps:

1. Determine the component, page, or API route where you want to trigger the email sending functionality.

2.
Import the `sendEmail` function from `utils/email.js` into the relevant file.

3.
Within the component, page, or API route, call the `sendEmail` function with the appropriate email details. For example:

    
    
import { sendEmail } from '../utils/email.js';

// Example integration in a Next.js page
export default function ContactFormPage() {
  const handleSubmit = async (event) => {
    event.preventDefault();

    // Process form data and prepare email details
    const emailDetails = {
      to: 'recipient@example.com',
      from: 'sender@example.com',
      subject: 'New contact form submission',
      message: '...',
    };

    try {
      await sendEmail(emailDetails);
      console.log('Email sent successfully!');
      // Perform any additional actions after successful email sending
    } catch (error) {
      console.error('Error sending email:', error);
      // Handle error case
    }
  };

  return (
    
{/* Form fields */}
); }
Copied ✔


Adjust the email details and the triggering mechanism based on your specific requirements.

Enabling Triggered Email Sending

To enable triggered email sending based on business logic, follow these steps:

1. Identify the events or conditions in your application where email notifications should be sent. For example:

  • After successful order placement, you want to send an order confirmation email to the customer.
  •  When a user requests a password reset, you want to send a password reset link to the user's registered email address.

2. Locate the relevant event handlers, listeners, or functions in your Next.js application where these conditions occur.

3.
Implement the `sendEmail` function in your code. Here's an example of how it could be defined:

    
    
async function sendEmail(recipient, subject, content) {
  // Code to send the email using your preferred email sending library or service
  // Make sure to handle any errors that may occur during the email sending process
}
		
    
Copied ✔


4. Within the identified event handlers or functions, call the `sendEmail` function with the necessary email details. For example:

    
    
// After a successful order placement
async function handleSuccessfulOrderPlacement(order) {
  // Code to handle the order placement logic

  // Trigger the email sending functionality
  const recipient = order.customerEmail;
  const subject = 'Order Confirmation';
  const content = 'Thank you for your order!';
  await sendEmail(recipient, subject, content);
}

// When a user requests a password reset
async function handlePasswordResetRequest(user) {
  // Code to handle the password reset logic

  // Trigger the email sending functionality
  const recipient = user.email;
  const subject = 'Password Reset';
  const content = 'Click the following link to reset your password: ';
  await sendEmail(recipient, subject, content);
}

		
    
Copied ✔


5. Remember to handle any errors that may occur during the email sending process and provide appropriate feedback or fallback options to your users.

Deployment Considerations

When deploying your Next.js application with email-sending functionality, consider the following deployment considerations for smooth operations and reliable email delivery:

  • Understand the limitations of AWS SES sending quotas, including maximum email limits and restrictions on recipient addresses, attachment sizes, and content types.
  • Monitor and manage your email sending limits by regularly tracking your sending volume, setting up notifications or alarms, and utilizing monitoring tools like AWS CloudWatch.
  • Implement rate limiting in Next.js to ensure compliance with AWS SES sending limits, using techniques such as token bucket algorithms or throttling and leveraging libraries or custom logic.

Error Handling and Logging:

Effective error handling and logging mechanisms are vital for identifying and resolving issues related to email sending. Consider the following practices:

  • Identify common errors and exceptions related to email sending, such as network issues or invalid addresses, and handle them gracefully with meaningful feedback to users.
  • Integrate logging mechanisms to capture relevant information about email-sending activities, including content, recipients, timestamps, and encountered errors or exceptions.
  • Utilize logging frameworks or services like AWS CloudWatch Logs to centralize and analyze logged data for debugging purposes.

Testing and Quality Assurance:

  • Perform unit tests to validate components and functions responsible for email sending, covering various scenarios and error handling.
  • Use AWS SES Sandbox Mode for integration testing, ensuring compliance with guidelines and addressing bounce or complaint notifications.
  • Implement email delivery monitoring and reporting, leveraging AWS SES features and analytics tools for actionable insights and optimization.

Pros and Cons

Pros of Sending Emails using AWS SES and Next.js:

  1. Scalable email infrastructure
  2. High email deliverability rates
  3. Robust and reliable AWS ecosystem integration
  4. Flexibility to customize email sending logic
  5. Reliable infrastructure for handling large email volumes

Cons of Sending Emails using AWS SES and Next.js:

  1. Doesn't provide delivery reports.
  2. Complex setup and maintenance process
  3. Potential cost implications for high email volumes
  4. Ongoing monitoring and maintenance required
  5. Limited template management (which you can get in SuprSend)

Replacing AWS SES Complexities with SuprSend

SuprSend lets you implement the AWS SES infrastructure capabilities while also letting you add on new capabilities which is not available in AWS SES. You can install SuprSend Node SDK and implement the workflow on our dashboard.

Don't want to do complex AWS SES API integrations manually? Check out this easier altenative method:

Go Here

  • With SuprSend, you can get a centralized notification delivery reports which is not possible in AWS SES. In the 'Logs' section, you can analyze each trigger, and notifications. It enables you to continuously monitor your notifications performance right from a single dashboard.
  • Setup is breeze with SuprSend, as you don't need to implement the complex AWS SES infrastructure. You can put the AWS SES API key in SuprSend's dashboard, and your integration is completed.
  • AWS SES doesn't provide you template creation and management capabilities in code, which is a necessary part of notification system. With SuprSend, you can build templates, test, deploy and run it via your AWS SES vendor in minutes right from code.
Need an alternative method to send emails without the setup hassles? Alternative Method - Send Transactional Emails in Next.js Using Any Email Provider Without API Integrations
Written by:
Anjali Arya
Product & Analytics, 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.