Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection timed out: connect

Email succeeded through Gmail using JDK 7 with below Gmail settings.

Go to Gmail Settings > Accounts and Import > Other Google Account settings > and under Sign-in & security

  1. 2-Step Verification: Off
  2. Allow less secure apps: ON
  3. App Passwords: 1 password (16 characters long), later replaced the current password with this.

used following maven dependencies:

spring-core:4.2.2
spring-beans:4.2.2
spring-context:4.2.2
spring-context-support:4.2.2
spring-expression:4.2.2
commons-logging:1.2

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

and my source code is:

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;
import java.util.List;
import java.util.Properties;

public class Email {

    public final void prepareAndSendEmail(String htmlMessage, String toMailId) {

        final OneMethod oneMethod = new OneMethod();
        final List<char[]> resourceList = oneMethod.getValidatorResource();

        //Spring Framework JavaMailSenderImplementation    
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.gmail.com");
        mailSender.setPort(465);

        //setting username and password
        mailSender.setUsername(String.valueOf(resourceList.get(0)));
        mailSender.setPassword(String.valueOf(resourceList.get(1)));

        //setting Spring JavaMailSenderImpl Properties
        Properties mailProp = mailSender.getJavaMailProperties();
        mailProp.put("mail.transport.protocol", "smtp");
        mailProp.put("mail.smtp.auth", "true");
        mailProp.put("mail.smtp.starttls.enable", "true");
        mailProp.put("mail.smtp.starttls.required", "true");
        mailProp.put("mail.debug", "true");
        mailProp.put("mail.smtp.ssl.enable", "true");
        mailProp.put("mail.smtp.user", String.valueOf(resourceList.get(0)));

        //preparing Multimedia Message and sending
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo(toMailId);
            helper.setSubject("I achieved the Email with Java 7 and Spring");
            helper.setText(htmlMessage, true);//setting the html page and passing argument true for 'text/html'

            //Checking the internet connection and therefore sending the email
            if(OneMethod.isNetConnAvailable())
                mailSender.send(mimeMessage);
            else
                JOptionPane.showMessageDialog(null, "No Internet Connection Found...");
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

}

Hope this will help someone.


As I said, there's nothing wrong with your code. If anything, just to do some testing, try to drop the Authentication part to see if that works:

    public void sendPlainTextEmail(String host, String port,
            final String userName, final String password, String toAddress,
            String subject, String message) throws AddressException,
            MessagingException {

        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
// *** BEGIN CHANGE
        properties.put("mail.smtp.user", userName);

        // creates a new session, no Authenticator (will connect() later)
        Session session = Session.getDefaultInstance(properties);
// *** END CHANGE

        // creates a new e-mail message
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        // set plain text message
        msg.setText(message);

// *** BEGIN CHANGE
        // sends the e-mail
        Transport t = session.getTransport("smtp");
        t.connect(userName, password);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
// *** END CHANGE

    }

That's the code I'm using every day to send dozens of emails from my application, and it is 100% guaranteed to work -- as long as smtp.gmail.com:587 is reachable, of course.


For all those who are still looking for the answer explained in a simple way, here is the answer:

Step 1: Most of the Anti Virus programs block sending of Email from the computer through an internal application. Hence if you get an error, then you will have to disable your Anti Virus program while calling these Email sending methods/APIs.

Step 2: SMTP access to Gmail is disabled by default. To permit the application to send emails using your Gmail account follow these steps

  1. Open the link: https://myaccount.google.com/security?pli=1#connectedapps
  2. In the Security setting, set ‘Allow less secure apps’ to ON.

Step 3: Here is a code snippet from the code that I have used and it works without any issues. From EmailService.java:

private Session getSession() {
    //Gmail Host
    String host = "smtp.gmail.com";
    String username = "[email protected]";
    //Enter your Gmail password
    String password = "";

    Properties prop = new Properties();
    prop.put("mail.smtp.auth", true);
    prop.put("mail.smtp.starttls.enable", "true");
    prop.put("mail.smtp.host", host);
    prop.put("mail.smtp.port", 587);
    prop.put("mail.smtp.ssl.trust", host);

    return Session.getInstance(prop, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
}

I have also written a blog post and a working application on GitHub with these steps. Please check: http://softwaredevelopercentral.blogspot.com/2019/05/send-email-in-java.html