Cannot send SMTP mail from AWS EC2

Viewed 5221

I am trying to send an email using SMTP. It works fine in my local. But it does not work when i built it on AWS EC2 server.

This is my code to config and send email!
Any idea for me?

try{

     Properties props = System.getProperties();
     props.put("mail.smtp.starttls.enable",true);
     props.put("mail.smtp.host","smtp.gmail.com");
     props.put("mail.smtp.user","test@gmail.com");
     props.put("mail.smtp.password","testpassword");
     props.put("mail.smtp.port","587");
     props.put("mail.smtp.auth",true);
     props.put("mail.smtp.ssl.trust", "*");

     String[] to = {toEmail};

     Session session = Session.getDefaultInstance(props, null);
     MimeMessage message = new MimeMessage(session);
     message.setFrom(new InternetAddress("test@gmail.com"));
     InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i=0; i < to.length; i++ ) { // changed from a while loop
            toAddress[i] = new InternetAddress(to[i]);
        }
        System.out.println("EMAIL TO:"+toEmail);

        for( int i=0; i < toAddress.length; i++) { // changed from a while loop
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }
        message.setSubject(subject);
        message.setText(content);
        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.gmail.com","test@gmail.com","testpassword");
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
  }
  catch(Exception ex){
         log.debug("send Email failed", ex);
  }
2 Answers

We were recently bit by this issue as well. AWS by default throttles the number of connections that can originate from ec2 instances. The limitation is part of the EC2 service itself. Ironically it doesn't show any mention of this as a "limit" under the limits section of the EC2 service. It is mentioned on the form though to have this limit removed from your account:

I'm having trouble sending email over port 25 of my Amazon Elastic Compute Cloud (Amazon EC2) instance, or I'm getting frequent timeout errors. How do I remove the port 25 throttle on my EC2 instance?

It's also mentioned on the AWS Service Limits page for EC2:

ss#1

The removal can be done in minutes once you submit the form to AWS.

References

Related