This is the code I am using to send an email:
@Override
public void sendEmail(String from, String to, String subject, String content) {
//we set the credentials
final String username = ConfigService.mailUserName;
final String password = ConfigService.mailPassword;
//we set the email properties
Properties props = new Properties();
props.put("mail.smtp.host", ConfigService.mailHost);
props.put("mail.smtp.socketFactory.port", ConfigService.mailSmtpSocketPort);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", ConfigService.mailSmtpPort);
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(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(content);
Transport.send(message);
LOG.info(" Email has been sent");
} catch (MessagingException e) {
LOG.error(" Email can not been sent");
e.printStackTrace();
}
}
When I run this I obtain the next error:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
I have seen another question related to this one here, but there is no accepted answer on that question. I can ping to smtp.gmail.com
and also I can access the gmail account with the credentials.
This is running in my machine.
Any idea what could be the problem?