Integrate Amazon SES with Spring Boot: Step-by-Step Guide for Sending Emails

Here's an example of how to use Amazon Simple Email Service (SES) with a Spring Boot application for sending transactional emails.

Here’s a step-by-step explanation of the workflow depicted in our diagram:

  1. User Sends HTTP Request

    • The user makes an HTTP POST request to the Spring Boot application at the endpoint /api/emails/send with the required parameters (from, to, subject, body).
  2. REST Controller Triggers Email Sending

    • The EmailController in the Spring Boot application receives the request and triggers the sendEmail() method.
  3. EmailController Calls EmailService

    • The EmailController delegates the task of sending the email to the EmailService by invoking its sendEmail(from, to, subject, body) method.
  4. EmailService Sends Request to Amazon SES

    • The EmailService creates a SendEmailRequest containing the email details (From, To, Subject, Body) and sends it to Amazon Simple Email Service (SES) for processing.
  5. Amazon SES Processes Email

    • Amazon SES processes the email request and sends a response back to the Spring Boot application indicating whether the email was successfully sent or if an error occurred.
  6. EmailService Acknowledges Response

    • The EmailService receives the response from Amazon SES and confirms that the email was sent successfully.
  7. Controller Sends Response to User

    • The EmailController sends an HTTP response back to the user with a success message, e.g., "Email sent successfully".

1. Prerequisites

  1. AWS Account: Set up and configure Amazon SES in the AWS Management Console.
    • Verify your sender email address or domain.
    • (Optional) Move out of the SES sandbox for unrestricted email sending.
  2. AWS SDK for Java: Include the AWS SDK dependencies in your project.
  3. IAM Role/Access Keys: Create an IAM user with SES permissions and obtain access and secret keys.

2. Maven Dependencies

Add the following dependencies to your pom.xml file:

<!-- AWS SDK for SES -->
    <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>ses</artifactId>
        <version>2.30.0</version>
    </dependency>

3. Configuration

Add your AWS credentials and region to application.yml or application.properties.

application.yml

aws:
  ses:
    region: us-east-1
    access-key: YOUR_ACCESS_KEY
    secret-key: YOUR_SECRET_KEY

4. Service Implementation

Create a service class to handle email sending:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.services.ses.model.*;

@Service
public class EmailService {

    private final SesClient sesClient;

    public EmailService(@Value("${aws.ses.access-key}") String accessKey,
                        @Value("${aws.ses.secret-key}") String secretKey,
                        @Value("${aws.ses.region}") String region) {
        AwsBasicCredentials awsCredentials = AwsBasicCredentials.create(accessKey, secretKey);
        this.sesClient = SesClient.builder()
                .region(Region.of(region))
                .credentialsProvider(StaticCredentialsProvider.create(awsCredentials))
                .build();
    }

    public void sendEmail(String from, String to, String subject, String body) {
        try {
            SendEmailRequest request = SendEmailRequest.builder()
                    .destination(Destination.builder()
                            .toAddresses(to)
                            .build())
                    .message(Message.builder()
                            .subject(Content.builder()
                                    .data(subject)
                                    .build())
                            .body(Body.builder()
                                    .text(Content.builder()
                                            .data(body)
                                            .build())
                                    .build())
                            .build())
                    .source(from)
                    .build();

            sesClient.sendEmail(request);
            System.out.println("Email sent successfully!");
        } catch (SesException e) {
            System.err.println("Failed to send email: " + e.getMessage());
            throw e;
        }
    }
}

5. Controller

Create a REST controller to trigger email sending:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/emails")
public class EmailController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/send")
    public String sendEmail(@RequestParam String from,
                            @RequestParam String to,
                            @RequestParam String subject,
                            @RequestParam String body) {
        emailService.sendEmail(from, to, subject, body);
        return "Email sent successfully!";
    }
}

6. Testing

  1. Run the Spring Boot application.
  2. Send a POST request to http://localhost:8080/api/emails/send with the required parameters:
    • from: Verified sender email address.
    • to: Recipient email address.
    • subject: Email subject.
    • body: Email body.

Testing using curl:

curl -X POST "http://localhost:8080/api/emails/send" \
     -d "from=verified_sender@example.com" \
     -d "to=recipient@example.com" \
     -d "subject=Hello from SES" \
     -d "body=This is a transactional email sent via Amazon SES."

7. Notes

  • Verify both sender and recipient emails in the SES sandbox.
  • To move out of the sandbox, request production access in the AWS SES console.
  • Use HTML content in the email body by modifying the Body object in the sendEmail method.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete