java - 在 Java 中使用 POP3 根据指定的日期时间检索电子邮件

标签 java jakarta-mail pop3

我收到了所有邮件,但我想根据日期提取邮件。

public void downloadEmailAttachments(String host, String port,String userName, String password) {
        Properties properties = new Properties();
        properties.put("mail.pop3.host", host);
        properties.put("mail.pop3.port", port);
        properties.put("mail.pop3.user",userName);
        properties.put("mail.password",password);

        // SSL setting
        properties.setProperty("mail.pop3.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.pop3.socketFactory.fallback", "false");
        properties.setProperty("mail.pop3.socketFactory.port",
                String.valueOf(port));

        Session session = Session.getDefaultInstance(properties);

        try {
            // connects to the message store
            Store store = session.getStore("pop3");
            store.connect(host,userName, password);//change here............

            Folder folderInbox = store.getFolder("INBOX");

            folderInbox.open(Folder.READ_ONLY);

          Message[] arrayMessages = folderInbox.getMessages();




             for (int i = 0; i < arrayMessages.length; i++) {
                Message message = arrayMessages[i];
                Address[] fromAddress = message.getFrom();
                String from = fromAddress[0].toString();
                Address[]toAdress=message.getAllRecipients();
                String to=toAdress[0].toString();
                String subject = message.getSubject();
                String sentDate = message.getSentDate().toString();
                String contentType = message.getContentType().toString();

                String messageContent = "";

                // store attachment file name, separated by comma
                String attachFiles = "";

                if (contentType.contains("multipart")) {
                    // content may contain attachments
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // this part is attachment
                            String fileName = part.getFileName();
                            attachFiles += fileName + ", ";
                            part.saveFile(saveDirectory + File.separator + fileName);

                        } else {
                            // this part may be the message content
                            messageContent = part.getContent().toString();
                        }
                    }

                    if (attachFiles.length() > 1) {
                        attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                    }
                } else if (contentType.contains("text/plain")
                        || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }

                // print out details of each message
                System.out.println("Message #" + (i + 1) + ":");
                System.out.println("\t From: " + from);
                System.out.println("\t to: " + to);
                System.out.println("\t Subject: " + subject);
                System.out.println("\t Sent Date: " + sentDate);
                System.out.println("\t Message: " + messageContent);
                System.out.println("\t Attachments: " + attachFiles);
            }

            // disconnect...............
            folderInbox.close(false);
            store.close();
        } catch (NoSuchProviderException ex) {
            System.out.println("No provider for pop3.");
            ex.printStackTrace();
        } catch (MessagingException ex) {
            System.out.println("Could not connect to the message store");
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

最佳答案

仅当您使用 IMAP 连接时,服务器才会搜索某个时间段或通常按时间搜索。 示例:

SearchTerm term = null;

Calendar cal = null;
cal = Calendar.getInstance();
Date minDate = new Date(cal.getTimeInMillis());   //get today date

cal.add(Calendar.DAY_OF_MONTH, 1);                //add 1 day
Date maxDate = new Date(cal.getTimeInMillis());   //get tomorrow date
ReceivedDateTerm minDateTerm = new ReceivedDateTerm(ComparisonTerm.GE, minDate);
ReceivedDateTerm maxDateTerm = new ReceivedDateTerm(ComparisonTerm.LE, maxDate);

term = new AndTerm(term, minDateTerm);            //concat the search terms
term = new AndTerm(term, maxDateTerm);

Message messages[] = folderInbox.search(term);    //search on the imap server

如果您不使用 IMAP 而使用 POP3,我想您唯一的选择是(在客户端)过滤您从服务器获取的整个消息列表,并对其进行迭代,就像 @user2310289 告诉您的那样:

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

希望对你有所帮助。

关于java - 在 Java 中使用 POP3 根据指定的日期时间检索电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19536386/

相关文章:

java - 当我尝试在虚拟设备上启动它时出现 tictactoe 错误

java - 需要在 Fedora 13/Linux 上安装和配置 Java JDK 和 Tomcat 的简单方法

java - ANDROID - session /数据库连接管理(社交应用)

java - SonarQube:更改此条件,使其不总是评估为 "false"(最终在 javax.mail 接收中)

php - imap_open() 无法使用 POP3 协议(protocol)打开流

java - 将 SortedList 比较器绑定(bind)到 TableView 比较器会删除排序

java - 电子邮件地址中的特殊字符抛出异常

java - 使用 Spring 的 JavaMailSender 发送的 Html 邮件没有主题和纯文本

.net - 处理收到的电子邮件

email - 使用 gmail 连接到 POP3 失败