SocketTimeoutException when connecting to Gmail via IMAP in Java

I’m trying to build a Java program that reads emails from Gmail using JavaMail API with IMAP protocol. However, I keep running into a SocketTimeoutException when attempting to establish the connection.

Here’s the code I’m currently using:

Properties config = new Properties();
config.put("mail.imap.host", "imap.gmail.com");
config.put("mail.imap.port", "993");
config.put("mail.imap.connectiontimeout", "5000");
config.put("mail.imap.timeout", "5000");

try {
    Session mailSession = Session.getInstance(config, new CustomAuthenticator());
    URLName gmailUrl = new URLName("imap://[email protected]:[email protected]");
    Store mailStore = mailSession.getStore(gmailUrl);
    if (!mailStore.isConnected()) {
        mailStore.connect();
    }
} catch (NoSuchProviderException ex) {
    ex.printStackTrace();
    System.exit(1);
} catch (MessagingException ex) {
    ex.printStackTrace();
    System.exit(2);
}

I’ve configured timeout settings to prevent indefinite waiting, but I’m still getting the timeout error. I notice that my CustomAuthenticator class also contains credentials, which seems to duplicate what’s in the URL. Is there a better approach to specify the IMAP protocol configuration? Any suggestions on what might be causing this timeout issue?

Your timeout settings are way too aggressive for Gmail’s IMAP server. I hit the same issue when I started with JavaMail - bumping the connection timeout to 30000ms fixed it right away. You’re also missing SSL config, which Gmail requires. Add mail.imap.ssl.enable=true to your properties or the connection won’t work. You’re doing authentication twice too - both URLName with credentials AND CustomAuthenticator. Pick one. I’d go with the authenticator since it keeps credentials separate from connection logic. If you’re still getting timeouts after this, try connecting without custom timeout values first to see if Gmail responds at all.

I’ve encountered a similar timeout issue with Gmail’s IMAP. Often, the root cause is related to network or firewall settings rather than the code itself. Your 5000ms timeout is quite short; consider increasing it to at least 30000ms to see if you can establish a connection. Additionally, it looks like you need to configure SSL, which is mandatory for Gmail. Just add mail.imap.ssl.enable=true to your properties. If possible, test your connection from a different network; this helped me realize that the corporate firewall was blocking IMAP ports. Also, for testing, you can activate less secure app access in Gmail, but for production, ensure you use app passwords.

5 seconds is way too short for Gmail IMAP - I bump mine up to 60000ms and haven’t had issues since. You’re also missing mail.imap.ssl.enable=true in your properties. Gmail blocks non-SSL connections, so that’s probably why it’s failing. Double-check if you’ve got 2FA turned on too - that’ll block the connection even with the right credentials.