Wednesday, February 10, 2016

Verifying Email Address on AWS SES

Amazon SES requires that you verify your email address or domain, to confirm that you own it and to prevent others from using it. This section discusses verifying individual email addresses. For information about domain verification, see Verifying Domains in Amazon SES.
With the exception of addresses containing labels (see below), you must verify each email address (or the domain of the email address) that you will use as a "From" or "Return-Path" address for your messages. Until your account is out of the Amazon SES sandbox, you must also verify the email address of every recipient except for the recipients provided by the Amazon SES mailbox simulator. For more information about the mailbox simulator, seeTesting Amazon SES Email Sending.

Sample

Note: You should have awscredentials.props in place. It would have access and secret key.

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.simpleemail.AWSJavaMailTransport;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient;
import com.amazonaws.services.simpleemail.model.ListVerifiedEmailAddressesResult;
import com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest;

/**
 * This sample demonstrates how to make basic requests to the Amazon Simple
 * Email Service using the the standard JavaMail API.
 *
 * Prerequisites: You must have a valid Amazon Web Services developer
 * account, and be signed up to use Amazon Simple Email Service. For more
 * information on Amazon Simple Email Service, see http://aws.amazon.com/ses .
 *
 * Important: Be sure to fill in your AWS access credentials in the
 * AwsCredentials.properties file before you try to run this sample.
 * http://aws.amazon.com/security-credentials
 *
 * @author sachin_nikam
 */
public class AWSJavaMailSample {

    /**
     * {@link LoggerFactory} instance
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(AWSJavaMailSample.class);

    /**
     * Email to address
     */
    private static final String TO = "sac10nikam@gmail.com";
    /**
     * Email from address
     */
    private static final String FROM = "sac10nikam@gmail.com";
    /**
     * Email body
     */
    private static final String BODY = "Hello Sachin!";
    /**
     * Email Subject
     */
    private static final String SUBJECT = "Hello Sachin!";

    /**
     * Public Constructor
     */
    private AWSJavaMailSample() {
        // No implementation
    }

    /**
     * Main method to verify email address.
     *
     * @param args
     *            The string array
     * @throws IOException
     *             The {@link IOException} instance
     * @throws MessagingException
     *             The {@link MessagingException} instance
     */
    public static void main(final String[] args) throws IOException, MessagingException {
        /*
         * Important: Be sure to fill in your AWS access credentials in the
         * AwsCredentials.properties file before you try to run this sample.
         * http://aws.amazon.com/security-credentials
         */
        final PropertiesCredentials credentials = new PropertiesCredentials(
                AWSJavaMailSample.class.getResourceAsStream("awscredentials.properties"));
        final AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials);

        /*
         * Before you can send email via Amazon SES, you need to verify that you
         * own the email address from which youĂ•ll be sending email. This will
         * trigger a verification email, which will contain a link that you can
         * click on to complete the verification process.
         */
        verifyEmailAddress(ses, FROM);

        /*
         * Setup JavaMail to use the Amazon Simple Email Service by specifying
         * the "aws" protocol.
         */
        final Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "aws");

        /*
         * Setting mail.aws.user and mail.aws.password are optional. Setting
         * these will allow you to send mail using the static transport send()
         * convince method. It will also allow you to call connect() with no
         * parameters. Otherwise, a user name and password must be specified in
         * connect.
         */
        props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
        props.setProperty("mail.aws.password", credentials.getAWSSecretKey());

        final Session session = Session.getInstance(props);

        try {
            // Create a new Message
            final Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(FROM));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
            msg.setSubject(SUBJECT);
            msg.setText(BODY);
            msg.saveChanges();

            // Reuse one Transport object for sending all your messages
            // for better performance
            final 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();
        } catch (AddressException e) {
            LOGGER.error(e.getMessage());
            LOGGER.debug("Caught an AddressException, which means one or more of your "
                    + "addresses are improperly formatted.");
            throw e;
        } catch (MessagingException e) {
            LOGGER.error(e.getMessage());
            LOGGER.debug("Caught a MessagingException, which means that there was a "
                    + "problem sending your message to Amazon's E-mail Service check the "
                    + "stack trace for more information.");
            throw e;
        }
    }

    /**
     * Sends a request to Amazon Simple Email Service to verify the specified
     * email address. This triggers a verification email, which will contain a
     * link that you can click on to complete the verification process.
     *
     * @param ses
     *            The Amazon Simple Email Service client to use when making
     *            requests to Amazon SES.
     * @param address
     *            The email address to verify.
     */
    private static void verifyEmailAddress(final AmazonSimpleEmailService ses, final String address) {
        final ListVerifiedEmailAddressesResult verifiedEmails = ses.listVerifiedEmailAddresses();
        if (verifiedEmails.getVerifiedEmailAddresses().contains(address))
            return;

        ses.verifyEmailAddress(new VerifyEmailAddressRequest().withEmailAddress(address));
        LOGGER.info("Please check the email address " + address + " to verify it");
    }
}