Search code examples
javanetwork-programmingcontent-management-systemjakarta-mailimap

JavaMail IMAP Connection Refused - Telnet works


I'm trying to use JavaMail in order to connect to an IMAP Server (on a remote virtual linux machine - Ubuntu 14 LTS) but I'm getting the following exception:

java.net.ConnectException: Connection refused

I've already tried to establish the connection via Telnet and everything works.

The JavaMail version I'm using is 1.5.5 (also tested with 1.4.7) and I'm using the following properties:

    Properties properties = System.getProperties();
    properties.setProperty("mail.imap.host", SERVER);
    properties.setProperty("mail.store.protocol", "imap");
    properties.put("mail.imap.port", PORT);

    Session session = Session.getInstance(properties, null);
    Store store = session.getStore("imap");
    store.connect(USERNAME, PASSWORD);

Notes:

  • It's working on my personal machine
  • It's working on another external machine
  • It's failing on the remote linux virtual machine
  • The IMAP server is on a different machine - which is accessible to all of the previous

I've done some research and some people told that it could be a firewall/blocking issue but how am I able to connect via Telnet?

Thanks.

Edited

The telnet command I've applied in the test-run:

telnet <server_ip> <port>

After this, the connection is successfuly established and I'm able to apply IMAP commands such as list status.

The output from javamail when it fails is the following:

java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.iap.Protocol.<init>(Protocol.java:107)
    at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:104)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:538)
    ... 12 more

Solution

  • I've found a solution!!

    I performed a network capture on the remote machine and I saw that for some reason the javamail api was using the default IMAP folder and not the one I've selected..

    Further tests revealed that changing the property value type to String instead of Integer solved this issue. It's important to notice that this didn't happen on other environments so I'm not sure the reason I had to make this change.