Include AWS SDK for Java
- Add the AWS SDK for Java dependencies to your project's build file. If you're using Maven, include the AWS SDK for SES in your `pom.xml`.
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>ses</artifactId>
<version>2.20.0</version>
</dependency>
Configure AWS Credentials
- Create a proper configuration for AWS credentials by placing them in the default AWS credentials file at `~/.aws/credentials` or using environment variables. Use IAM roles if deploying in an AWS environment like EC2.
Initialize the SES Client
- Create a client instance of Amazon Simple Email Service (SES). Use the `SesClient.builder` method to construct an SES client.
import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.regions.Region;
SesClient sesClient = SesClient.builder()
.region(Region.US_EAST_1) // Specify your preferred AWS region
.build();
Prepare Email Content
- Compose the email subject and body. Consider using HTML for better formatting options. Use templates if necessary to personalize content.
String subject = "Welcome to Our Service";
String htmlBody = "<h1>Welcome!</h1><p>Thank you for joining our community.</p>";
String textBody = "Thank you for joining our community!";
Set Up Bulk Email Requests
- Utilize the BulkEmailDestination API to define the recipients and their corresponding personalization attributes.
import software.amazon.awssdk.services.ses.model.*;
List<BulkEmailDestination> destinations = new ArrayList<>();
destinations.add(BulkEmailDestination.builder()
.destination(Destination.builder()
.toAddresses("recipient1@example.com")
.build())
.replacementTags(Tag.builder().name("Name").value("John").build())
.build());
destinations.add(BulkEmailDestination.builder()
.destination(Destination.builder()
.toAddresses("recipient2@example.com")
.build())
.replacementTags(Tag.builder().name("Name").value("Jane").build())
.build());
Send Bulk Emails
- Create a `SendBulkTemplatedEmailRequest` object and send the bulk email. Handle exceptions and confirm successful processing.
try {
SendBulkTemplatedEmailRequest bulkEmailRequest = SendBulkTemplatedEmailRequest.builder()
.source("your-email@example.com")
.template("MyTemplate") // Use pre-created SES template if desired
.destinations(destinations)
.defaultTemplateData("{ \"name\":\"Customer\" }")
.build();
SendBulkTemplatedEmailResponse response = sesClient.sendBulkTemplatedEmail(bulkEmailRequest);
System.out.println("Email sent successfully: " + response.status());
} catch (SesException e) {
e.printStackTrace();
}
Clean Up
- Close the SES client to release resources when done sending emails.
sesClient.close();
Best Practices
- Make sure to adhere to AWS SES sending limits and guidelines to ensure proper delivery rates.
- Consider handling bounces and complaints through SES feedback notification for maintaining lists quality.