AWS Developer Tools Blog

Sending Email with JavaMail and AWS

The Amazon Simple Email Service and the JavaMail API are a natural match for each other. Amazon Simple Email Service (Amazon SES) provides a highly scalable and cost-effective solution for bulk and transactional email-sending. JavaMail provides a standard and easy-to-use API for sending mail from Java applications. The AWS SDK for Java brings these two together with an AWS JavaMail provider, which gives developers the power of Amazon SES, combined with the ease of use and standard interface of the JavaMail API.

Using the AWS JavaMail provider from the SDK is easy. The following code shows how to set up a JavaMail session and send email using the AWS JavaMail transport.

/*
 * Setup JavaMail to use Amazon SES by specifying
 * the "aws" protocol and our AWS credentials.
 */
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
props.setProperty("mail.aws.password", credentials.getAWSSecretKey());

Session session = Session.getInstance(props);

// Create a new Message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("foo@bar.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("customer@company.com));
msg.setSubject("Hello AWS JavaMail World");
msg.setText("Sending email with the AWS JavaMail provider is easy!");
msg.saveChanges();

// Reuse one Transport object for sending all your messages
// for better performance
Transport t = new AWSJavaMailTransport(session, null);
t.connect();
t.sendMessage(msg, null);

// Close your transport when you're completely done sending
// all your messages.
t.close();

You can find the complete source code for this sample in the samples directory of the SDK, or go directly to it on GitHub.

The full sample also demonstrates how to verify email addresses using Amazon SES, a necessary prerequisite for sending email to those addresses until you request full production access to Amazon SES. See the Amazon Simple Email Service Developer Guide for more information on Verifying Email Addresses and Requesting Production Access.