1
votes

I am trying to connect to locally hosted email POP3 inbox and display emails in the mailbox, but I keep getting error:

Exception in thread "main" javax.mail.MessagingException: Connect failed; nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:209)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at com.kami.utils.MailClient.checkInbox(MailClient.java:33)
at com.kami.Main.main(Main.java:38)

My class looks like this:

public class MailClient {
    private String host;
    private String username;
    private String password;
    private String provider;
    protected Session session;

    public MailClient() {
        Properties props = new Properties();

        this.host = "localhost";
        this.username = "unix-user";
        this.password = "unix-password";
        this.provider = "pop3";

        this.session = Session.getDefaultInstance(props, null);
    }

    public void checkInbox() throws MessagingException, IOException {
        Store store = session.getStore(provider);
        store.connect(host, username, password); //This is line 33
        Folder inbox = store.getFolder("inbox");
        inbox.open(Folder.READ_ONLY);
        Message[] messages = inbox.getMessages();

        for(Message message : messages){
            System.out.println(message.getReceivedDate());
            System.out.println(message.getSubject());
        }

        inbox.close(true);
        store.close();
    }
}

It is locally hosted email server using Dovecot IMAP/POP3 Server Version 2.2.9 and Postfix Mail Server Postfix version 2.11.0

2
AFAIK the java pop3 implementation is for connected email boxes. Are you trying to connect an already downloaded pop3 mailbox ?Xvolks
Connecting to one that is locally hosted, like I can send email from it like so: props.put("mail.smtp.host", "localhost");Shepard
Locally hosted is confusing to me. Have you a mail server running on your linux box (pop3/pop3s service is running) ?Xvolks
Correct, Dovecot IMAP/POP3 Server Version 2.2.9 and Postfix Mail Server Postfix version 2.11.0Shepard
Hans Poo answer makes sense in this case. So check in your code if IP address and port are correct.Xvolks

2 Answers

1
votes

First telnet 110 port in your machine to check if the service is running there. In my laptop i don't have a pop3 server running, and this is the result:

hans@andes:~$ telnet localhost 110
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused

If the connection succeed, follow the protocol authentication of pop3 with your own data:

hans@andes:~$ telnet mail.foo.com 110
Trying X.X.X.X...
Connected to mail.foo.com.
Escape character is '^]'.
+OK mail.foo.com POP3 server ready
user fooUser
+OK hello fooUser, please enter your password
pass fooPassword
+OK server ready

In your case telnet localhost; note too that you only should issue the commands: telnet, user and pass. The rest is the response from the server.

If all this works, the problem is on something with your java configuration, check the documentation and samples from the library.

0
votes

The below method will fetch messages from a pop mailbox (given _Host=localhost, _User=unix-user, _Password=unix-password, _Protocol="pop3"). However you must be sure of a few things: 1) "localhost" is running a "pop3" server and not a "pop3s" (secure protocol) server; 2) the "pop3" server on "localhost" is listening on the default port 3) "unix-user" has a pop3 mailbox

Based on your follow-up, it seems like you are expecting to be able to send mail from the pop3 account. This is not how it works as pop3 is only a way to retrieve messages, not send them. To send mail, you need to establish a separate connection to an SMTP server.

  public Message[] getMessages(int maxCount)
      throws MessagingException
  {
    // Get a Session object
    Properties props = new Properties();
    Session session = Session.getInstance(props);

    // Get a Store object
    Store store = session.getStore(_protocol);

    // Connect
    store.connect(_host,_user,_password);

    // Open a Folder
    Folder folder = store.getFolder(_mailbox);
    if (folder == null || !folder.exists())
        throw new ApplicationException("Invalid mailbox");

    //Gets up to maxCount messages from the pop box
    folder.open(Folder.READ_WRITE);
    Message[] messages = Monitor.EMPTY_MESSAGE_ARRAY;
    int toMessageIndex=folder.getMessageCount();
    if (toMessageIndex > 0) {
      if (toMessageIndex > maxCount)
        toMessageIndex = maxCount;
      messages = folder.getMessages(1,toMessageIndex);
    }

    // Go through all the new messages and make sure they are loaded. Use the outputStream
    //to force all information to be downloaded.
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    for (int i = 0; i < messages.length && shouldRun(); i++) {
      try {
        //Force the download of all message information
        bos.reset();
        messages[i].writeTo(bos);
        getLog().enter(
          this,
          "[readAndClearInBox] Read message to " + messages[i].getAllRecipients()[0].toString());

      } catch (Exception mex) {
        getLog().error(this, mex, "[readAndClearInBox] Message exception");
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        try {
          Monitor.dumpEnvelope(getLog(), pw, messages[i]);
        } catch (Exception ex) {
          getLog().error(this, mex, "[readAndClearInBox] Could only display faulty message.");
        } finally {
          pw.flush();
          getLog().enter(this, "[readAndClearInBox]" + sw.toString());
        }
      } finally {
        //Mark the message for deletion
        messages[i].setFlag(Flags.Flag.DELETED, true);
      }
    }

    //Close folder and expunge all deleted messages, unless the read was aborted
    if (shouldRun()) {
      getLog().enter(this,"Found " + messages.length + " messages; closing inbox.");
      folder.close(true);
      store.close();
      return messages;
    } else {
      getLog().enter(this,"Found " + messages.length + " messages; closing inbox without expunging.");
      folder.close(false);
      store.close();
      _bShouldRun = true;
      return Monitor.EMPTY_MESSAGE_ARRAY;
    }
  }