0
votes

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?

1
It is not a duplicate because none of the answers in the question you mention solve my problem. Anyway, thanks for the linkftrujillo

1 Answers

0
votes

I have been experiencing this issue when debugging using NetBeans, even executing the actual jar file. Antivirus would block sending email. You should temporarily disable your antivirus during debugging or exclude NetBeans and the actual jar file from being scanned. In my case, I'm using Avast.

See this link on how to Exclude : How to Add File/Website Exception into avast! Antivirus 2014

It works for me.