Javamail未读消息返回最后的消息而不是未读消息

时间:2012-10-19 04:53:48

标签: java javamail

这是我的代码,应该是获取未读消息。但是它会返回收件箱中的最后一条消息。有什么建议吗?

import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;
import java.util.*;
import com.sun.mail.pop3.POP3SSLStore;

public class MailClient {
public static void main(String[] args) {
    try {
      Properties props = new Properties();
      props.setProperty("mail.pop3.connectionpooltimeout", "3000");
      props.setProperty("mail.pop3.connectiontimeout", "3000");
      props.setProperty("mail.pop3.timeout", "3000");

      Session session;

          URLName url = new URLName("pop3","pop.gmail.com",995,"","email@gmail.com","pwd");
    session = Session.getInstance(props, null);
    Store store = new POP3SSLStore(session,url);
    store.connect();

    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);

    Flags seen = new Flags(Flags.Flag.SEEN);
    FlagTerm unseenFlagTerm = new FlagTerm(seen,false);
    Message message[] = folder.search(unseenFlagTerm); 

    for (int i=0, n = message.length;i<20;i++) {
        System.out.println("Message " + (i + 1));
                    System.out.println("From : " + message[i].getFrom()[0]);
                    System.out.println("Subject : " + message[i].getSubject());
                    System.out.println("Sent Date : " + message[i].getSentDate());
    }
    folder.close(false);
    store.close();
    }
    catch (MessagingException e) {
            System.out.println("Error: " + e);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

POP3协议不支持任何标志,因此无法告诉您是否已读取消息。请参阅javadocs for the com.sun.mail.pop3 package for more information

答案 1 :(得分:0)

您可以尝试按照以下方式使用并尝试一下;

int messageCount =  folder.getUnreadMessageCount();

if(messageCount>0){
 Message[] messages = folder.getMessages();
}