DEV Community

AWS SES with a NestJS Backend to Send Email Verifications

In my latest project, I needed to set up email verification to make sure users are providing valid email addresses when signing up. To do this, I integrated AWS SES (Simple Email Service) with my NestJS backend to send verification emails with a code that users could use to confirm their email addresses.

If you're working on something similar or just want to know how it works, let me walk you through the process. I'll keep it simple and personal to make it easy to understand.

What is AWS SES?

AWS SES (Simple Email Service) is a cloud-based email service by AWS that lets you send emails easily and at scale. You can use it to send transactional emails, marketing emails, or, in my case, verification emails.

Why Use AWS SES for Email Verification?

There are a few reasons I chose AWS SES for this project:

  • Reliable and high deliverability - Fewer emails end up in the spam folder
  • Scalable - Works even if your app grows and needs to send more emails
  • Cost-effective - Pay only for what you use

Setting Up AWS SES

The first step is setting up AWS SES in your AWS account. Here's what I did:

1. Create an AWS Account

If you don't have one yet, sign up at AWS.

2. Verify Your Domain or Email

In the SES console, I verified the domain that my app's emails would come from. Alternatively, you can verify a single email address, but verifying a domain is better for production apps.

3. Move Out of SES Sandbox

By default, AWS SES puts new accounts in a sandbox, which limits the number of emails you can send. I requested production access to remove these limits.

4. Obtain AWS Credentials

To use AWS SES in my NestJS backend, I needed my Access Key and Secret Key.

Installing AWS SDK in NestJS

Once AWS SES was ready, the next step was integrating it into my NestJS backend. First, I installed the AWS SDK for JavaScript:

npm install @aws-sdk/client-ses
Enter fullscreen mode Exit fullscreen mode

This package allows my NestJS application to interact with AWS SES to send emails.

Writing the NestJS Service to Send Emails

Next, I wrote a service in my NestJS app to handle the sending of verification emails. Here's a simple version of the code:

import { Injectable } from '@nestjs/common';
import { SESClient, SendEmailCommand } from '@aws-sdk/client-ses';

@Injectable()
export class EmailService {
  private sesClient: SESClient;

  constructor() {
    this.sesClient = new SESClient({ region: 'your-region' });
  }

  async sendVerificationEmail(email: string, code: string): Promise<void> {
    const params = {
      Source: 'your-verified-email@yourdomain.com',
      Destination: {
        ToAddresses: [email],
      },
      Message: {
        Body: {
          Text: { Data: `Your verification code is: ${code}` },
        },
        Subject: { Data: 'Email Verification' },
      },
    };

    const command = new SendEmailCommand(params);
    await this.sesClient.send(command);
  }
}
Enter fullscreen mode Exit fullscreen mode

How It Works:

  • I initialized the SESClient with my AWS region
  • The sendVerificationEmail method takes the recipient's email and a verification code as inputs
  • The email contains a subject line ("Email Verification") and a message body with the verification code
  • The SendEmailCommand sends the email via AWS SES

Calling the Service from the Controller

Next, I created a controller that handles requests from the frontend. When a user registers or requests a verification email, this controller sends the email:

import { Controller, Post, Body } from '@nestjs/common';
import { EmailService } from './email.service';

@Controller('auth')
export class AuthController {
  constructor(private readonly emailService: EmailService) {}

  @Post('send-email-verification')
  async sendVerificationEmail(@Body('email') email: string) {
    const verificationCode = this.generateVerificationCode();
    await this.emailService.sendVerificationEmail(email, verificationCode);
    return { message: 'Verification email sent' };
  }

  private generateVerificationCode(): string {
    return Math.floor(100000 + Math.random() * 900000).toString(); // 6-digit code
  }
}
Enter fullscreen mode Exit fullscreen mode

How It Works:

  • The AuthController listens for a POST request at the /auth/send-email-verification endpoint
  • It calls the EmailService to send the verification email to the user's email address with a 6-digit verification code
  • The verification code is randomly generated as a 6-digit number

Testing the Integration

After setting everything up, I tested the functionality. I used Postman to make a request to the /auth/send-email-verification endpoint with a test email. Sure enough, the email showed up in my inbox with the verification code.

Conclusion

Setting up email verification with AWS SES and NestJS is straightforward once you understand the pieces involved. The combination provides a reliable, scalable solution for email verification that can grow with your application.

Key Takeaways:

  • AWS SES provides reliable email delivery at scale
  • The AWS SDK makes integration with NestJS simple
  • Always verify your domain for production use
  • Remember to request production access to move out of the SES sandbox

Feel free to adapt this setup to your specific needs, such as using HTML templates for prettier emails or storing verification codes in a database for validation.

๐Ÿ‘จโ€๐Ÿ’ป Connect with me:
๐Ÿ“Œ LinkedIn
๐Ÿ“‚ GitHub
๐Ÿ–ฅ๏ธ Website

Top comments (0)