Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot send SMTP mail from AWS EC2

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","[email protected]");
     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("[email protected]"));
     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","[email protected]","testpassword");
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
  }
  catch(Exception ex){
         log.debug("send Email failed", ex);
  }
like image 227
J. Henry Avatar asked Dec 18 '25 20:12

J. Henry


1 Answers

AWS EC2 does not allow normal use of port 25 - the SMTP port.

It is severely throttled.

If you make very very light use of it then you might see sending email off the AWS account working occassionally. But generally it is not reliable

To resolve this problem there are two options

  1. use AWS SES simple email service. Or SNS for some really simple use cases
  2. ask AWS support to remove the restriction https://aws-portal.amazon.com/gp/aws/html-forms-controller/contactus/ec2-email-limit-rdns-request
like image 169
Vorsprung Avatar answered Dec 21 '25 12:12

Vorsprung