In this blog article, we’ll delve into using Amazon Simple Email Service (SES) to send emails, both with and without attachments, directly from your applications. SES is a cost-effective, flexible, and scalable email service offered by AWS.

Let’s explore how to leverage its capabilities.

1. Set up AWS SES

  • If you haven’t already, create an AWS account.
  • Navigate to the SES console and verify your email address or domain. This is important, especially if you’re in the SES sandbox, to ensure deliverability.
  • Obtain your AWS access key ID and secret access key. These credentials will be used to authenticate your application with AWS.

2. Include the AWS SDK in Your Project

  • Add the AWS SDK for Java to your project. If you’re using Maven, include the following dependency in your pom.xml:
<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-ses</artifactId>
    <version>1.12.540</version> 
</dependency>
  • Adjust the version if needed.

3. Create the Email Service

  • Let’s craft a service to handle email sending using the AWS SDK.
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.*;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Properties;

@Service
public class AwsSesEmailService {

    private final AmazonSimpleEmailService sesClient;

    public AwsSesEmailService() {
        BasicAWSCredentials credentials = new BasicAWSCredentials("your-access-key-id", "your-secret-access-key");
        sesClient = AmazonSimpleEmailServiceClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(Regions.YOUR_PREFERRED_REGION) 
                .build();
    }

    public void sendSimpleEmail(String to, String subject, String text) {
        SendEmailRequest request = new SendEmailRequest()
                .withDestination(new Destination().withToAddresses(to))
                .withMessage(new Message()
                        .withBody(new Body().withText(new Content().withCharset("UTF-8").withData(text)))
                        .withSubject(new Content().withCharset("UTF-8").withData(subject)))
                .withSource("your-verified-email@example.com"); 

        sesClient.sendEmail(request);
    }

    public void sendEmailWithAttachment(String to, String subject, String text, String attachmentPath) throws MessagingException, IOException {
        Session session = Session.getDefaultInstance(new Properties());
        MimeMessage message = new MimeMessage(session);

        message.setSubject(subject, "UTF-8");
        message.setFrom(new InternetAddress("your-verified-email@example.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(text, "text/plain; charset=UTF-8");

        MimeBodyPart attachmentPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentPath);
        attachmentPart.setDataHandler(new DataHandler(source));
        attachmentPart.setFileName(source.getName());

        MimeMultipart multipart = new MimeMultipart();
        multipart.addBodyPart(textPart);
        multipart.addBodyPart(attachmentPart);

        message.setContent(multipart);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        message.writeTo(outputStream);

        RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));

        SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
        sesClient.sendRawEmail(rawEmailRequest);
    }
}
  • Replace the placeholders with your actual AWS credentials and verified email address.
  • Choose the appropriate AWS region for your SES setup.

4. Use the Email Service

  • Similar to the previous example, you can autowire this AwsSesEmailService and use it to send emails.
@Autowired
private AwsSesEmailService awsSesEmailService;

// ...

awsSesEmailService.sendSimpleEmail("recipient@example.com", "Hello from SES", "This is a test email using AWS SES.");

// ...

try {
    awsSesEmailService.sendEmailWithAttachment("recipient@example.com", "SES Report", "Please find the attached report.", "/path/to/report.pdf");
} catch (MessagingException | IOException e) {
    // Handle exceptions
}

Important Considerations:

  • Make sure your AWS credentials are secure and not exposed in your code or version control.
  • Be mindful of SES sending limits, especially if you’re in the sandbox.
  • Monitor your email sending reputation to maintain good deliverability.
  • Implement error handling and logging to troubleshoot any issues that may arise.

By following these steps, you can effectively utilize AWS SES to send emails, with or without attachments, directly from your Java applications. SES provides a robust and scalable solution for managing your email communication needs.


Discover more from GhostProgrammer - Jeff Miller

Subscribe to get the latest posts sent to your email.

By Jeffery Miller

I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.