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);
}
