I am trying to send an email from a gmail account from windows server 2016 from a Java application and I get the error : "Could not connect to SMTP host: smtp.gmail.com, port: 587."
When trying on my local machine, which runs windows 10, the code works perfectly. I have used mail enable and port 587 is enabled and also used as an alternate port to listen to for SMTP. Also, I configured an inbound rule for this port on windows server. I still have the same error. Does anyone know what I can do ?
I will also add the code.
package email;
import java.sql.Timestamp;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GoogleMail {
public void sendEmail(String emailContent) {
final String username = "findyourbets2020@gmail.com";
final String password = "*********";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("findyourbets2020@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("testemail@gmail.com"));
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
message.setSubject("Application Failed at" + timestamp);
message.setText(emailContent);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}