Sending Email with Multiple Attachments using Amazon SES in Java Spring Boot
In this example, you will learn how to send a plain-text or HTML-based email with multiple attachments using Amazon SES in Java Spring Boot.
Follow these steps to achieve this:
- Setting up Amazon SES:
- Login to the AWS Management Console and open the AWS SES console at https://console.aws.amazon.com/ses.
- Create identity.
- Verify your email address with Amazon SES.
- Get your AWS credentials.
- Adding Dependency:
- Adding Configuration:
- Creating a Method for Sending an Email with Multiple Attachments:
Add Java SDK for Amazon SES dependency to your project from maven.
For Maven:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-ses</artifactId> <version>1.12.564</version> </dependency>
For Gradle:
implementation 'org.springframework.boot:spring-boot-starter-mail' implementation group: 'com.amazonaws', name: 'aws-java-sdk-ses', version: '1.12.564'
Create a class named AwsConfig and annotate it with @Configuration annotation. Add a method that returns an instance of AmazonSimpleEmailService class and annotate it with @Bean annotation. The following code shows how to do so:
package com.example.app.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
@Configuration
public class AwsConfig {
public AWSStaticCredentialsProvider awsCredentials() {
BasicAWSCredentials credentials =
new BasicAWSCredentials("your-aws-access-key", "your-aws-access-secret");
return new AWSStaticCredentialsProvider(credentials);
}
@Bean
public AmazonSimpleEmailService getAmazonSimpleEmailService() {
return AmazonSimpleEmailServiceClientBuilder.standard().withCredentials(awsCredentials())
.withRegion("us-east-1").build();
}
}
The following code demonstrates how to send an email with multiple attachments using Amazon SES in Java:
Note: HTML based email content only support inline style css.
package com.example.app.aws.ses;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.model.RawMessage;
import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
import jakarta.activation.FileDataSource;
import jakarta.mail.Message.RecipientType;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
@Component
public class EmailService3 {
@Autowired
public AmazonSimpleEmailService amazonSimpleEmailService;
public void sendEmailWithMultipleAttachments() {
Session session = Session.getInstance(new Properties(System.getProperties()));
MimeMessage mimeMessage = new MimeMessage(session);
String emailContent =
"<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + " <meta charset=\"utf-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
+ " <title>Example HTML Email with multiple attachents</title>\n" + "</head>\n"
+ "<body style=\"background: whitesmoke; padding: 30px; height: 100%\">\n"
+ "<h5 style=\"font-size: 18px; margin-bottom: 6px\">Dear example,</h5>\n"
+ "<p style=\"font-size: 16px; font-weight: 500\">Greetings from TutorialsBuddy</p>\n"
+ "<p>This is a simple html based email with multiple attachments.</p>\n" + "</body>\n"
+ "</html>";
// link to files
String filePath1 = "C:\\Users\\documents\\java-tutorials.pdf";
String filePath2 = "C:\\Users\\documents\\python-tutorials.pdf";
String filePath3 = "C:\\Users\\documents\\react-tutorials.pdf";
String filePath4 = "C:\\Users\\documents\\php-tutorials.pdf";
List<String> files = new ArrayList<>();
files.add(filePath1);
files.add(filePath2);
files.add(filePath3);
files.add(filePath4);
try {
mimeMessage.setSubject("Test Email", "UTF-8");
mimeMessage.setFrom("example@tutorialsbuddy.com");
mimeMessage.setRecipients(RecipientType.TO, "receiver@gmail.com");
MimeMultipart msgBody = new MimeMultipart("alternative");
MimeBodyPart wrap = new MimeBodyPart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(emailContent, "text/html; charset=UTF-8");
msgBody.addBodyPart(htmlPart);
wrap.setContent(msgBody);
MimeMultipart msg = new MimeMultipart("mixed");
mimeMessage.setContent(msg);
msg.addBodyPart(wrap);
// Add multiple files to attachment
for (int i = 0; files.size() > i; i++) {
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(files.get(i));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("file" + i + ".pdf");
msg.addBodyPart(messageBodyPart);
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mimeMessage.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
amazonSimpleEmailService.sendRawEmail(rawEmailRequest);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}