从gmail搜索电子邮件无法正常工作

时间:2015-09-08 04:50:48

标签: java email gmail javamail

我按照这个:Reading email from gmail is not working我可以获取所有电子邮件。但是,当我使用搜索参数时,我总是得到0结果。这就是我试过的:

  Date d1 = new DateTime(date.getTime()).toLocalDate().toDate();
  Date d2 = new DateTime(date.getTime()).plusDays(-30).toLocalDate().toDate();
  SearchTerm olderThan = new ReceivedDateTerm(ComparisonTerm.LT, d1);
  SearchTerm newerThan = new ReceivedDateTerm(ComparisonTerm.GT, d2);
  SearchTerm andTerm = new AndTerm(olderThan, newerThan);

  Message[] messages = emailFolder.search(andTerm);

如果我将最后一行更改为

  Message[] messages = emailFolder.getMessages();

一切正常,我收到所有电子邮件。我的收件箱中收到了过去30天内的电子邮件。我的搜索逻辑有问题吗?

1 个答案:

答案 0 :(得分:1)

您缺少下面的代码行,您必须覆盖match方法并将条件放在那里

    // creates a search criterion
    SearchTerm searchCondition = new SearchTerm() {
        @Override
        public boolean match(Message message) {
            try {
                if (message.getSubject().contains(keyword)) {
                    return true;
                }
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
            return false;
        }
    };

    // performs search through the folder
    Message[] foundMessages = folderInbox.search(searchCondition);

    for (int i = 0; i < foundMessages.length; i++) {
        Message message = foundMessages[i];
        String subject = message.getSubject();
        System.out.println("Found message #" + i + ": " + subject);
    }

编辑: -

SearchTerm andTerm = null;
andTerm = new AndTerm(andTerm, olderThan);  //concat the search terms
andTerm = new AndTerm(andTerm, newerThan );
Message messages[] = folderInbox.search(andTerm);    //search on the imap server

编辑1: -

for (Message message : messages) {
    if (message.getSentDate().after(olderThan) && message.getSentDate().before(newerThan))
       {
          //do whatever you want with your filtered by period message
       } 
}