连接到本地POP3收件箱Java

时间:2016-02-29 15:05:09

标签: java email javamail pop3 dovecot

我正在尝试连接到本地托管的电子邮件POP3收件箱并在邮箱中显示电子邮件,但我一直收到错误:

  

线程中的异常" main" javax.mail.MessagingException:连接失败;     嵌套异常是:
      java.net.ConnectException:连接被拒绝了       在com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:209)
      在javax.mail.Service.connect(Service.java:295)
      在javax.mail.Service.connect(Service.java:176)
      在com.kami.utils.MailClient.checkInbox(MailClient.java:33)
      在com.kami.Main.main(Main.java:38)

我的班级看起来像这样:

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();
    }
}

使用Dovecot IMAP / POP3服务器版本2.2.9和Postfix Mail Server Postfix版本2.11.0本地托管的电子邮件服务器

2 个答案:

答案 0 :(得分:1)

计算机中的第一个telnet 110端口,以检查服务是否在那里运行。在我的笔记本电脑中,我没有运行pop3服务器,结果就是这样:

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

如果连接成功,请使用您自己的数据跟踪pop3的协议身份验证:

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

在你的情况下telnet localhost;另请注意,您只应发出命令:telnet,user和pass。其余的是来自服务器的响应。

如果所有这些都有效,那么问题出在您的java配置上,请查看库中的文档和示例。

答案 1 :(得分:0)

以下方法将从pop邮箱中获取邮件(给定_Host = localhost,_User = unix-user,_Password = unix-password,_Protocol =" pop3")。但是你必须确定一些事情: 1)" localhost"正在运行一个" pop3"服务器,而不是" pop3s" (安全协议)服务器; 2)" pop3"服务器on" localhost"正在侦听默认端口 3)" unix-user"有一个pop3邮箱

根据您的后续行动,您似乎希望能够从pop3帐户发送邮件。这不是它的工作原理,因为pop3只是一种检索消息而不是发送消息的方法。要发送邮件,您需要建立与SMTP服务器的单独连接。

  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;
    }
  }