sending an attachment with Amazon SES using Java

Sometimes data scientists need to write software that sends out automated e-mails, and sometimes those e-mails must carry attachments. Here is how to do so in Java using Amazon’s Simple Email Service (SES), which is an inexpensive outbound email service built on Amazon’s cloud infrastructure.

Note: Be sure to log into Amazon SES and verify the recipient domain for your chosen host region before trying to run these steps. In the code below, the host region is set to “us-west-2”.

First, load the necessary libraries:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import com.amazonaws.services.simpleemail.AWSJavaMailTransport;

Next, specify the content of the e-mail and Amazon AWS credentials:

String fileToAttachPath = "/home/username/test.xls";
String fileNameInEmail = "test.xls";
String fileMime = "application/excel";
String from = "email address";
String to = "email address"; 
String body = "This is an e-mail text.";
String bodyMime = "text/plain";
String subject = "This is a subject.";
String accessKeyId = "Your AWS access key ID";
String secretKey = "Your AWS secret key";
String host = "email.us-west-2.amazonaws.com";

Load the file to attach into memory:

byte[] fileContent = null;
File file = new File(fileToAttachPath);
FileInputStream fin = null;
try {
	fin = new FileInputStream(file);
	fileContent = new byte[(int) file.length()];
	fin.read(fileContent);
} catch (FileNotFoundException e) {
	System.out.println("File not found.");
} catch (IOException ioe) {
	System.out.println("Exception reading file.");
} finally {
	try {
		if (fin != null) {
			fin.close();
		}
	} catch (IOException ioe) {
		System.out.println("Error while closing file.");
	}
}

Create a properties object for use by the AWS session:

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", accessKeyId);
props.setProperty("mail.aws.password", secretKey);
props.setProperty("mail.aws.host", host);

Create the e-mail message and transport:

Session AWSsession = Session.getInstance(props);
AWSJavaMailTransport AWSTransport = new AWSJavaMailTransport(AWSsession, null);
AWSTransport.connect();
MimeMessage message = new MimeMessage(AWSsession);
message.setFrom(new InternetAddress(from));
message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);

Generate the body of the e-mail message:

Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(body, bodyMime);
multipart.addBodyPart(messageBodyPart)

Add the attachment:

messageBodyPart = new MimeBodyPart();
ByteArrayDataSource source = new ByteArrayDataSource(fileContent, fileMime);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileNameInEmail);
multipart.addBodyPart(messageBodyPart);

Finally, send the message:

message.setContent(multipart);
message.saveChanges();
AWSTransport.sendMessage(message, null);

Leave a Reply

Your email address will not be published.