如何使用 Java 读取我的 Gmail 帐户的邮件接收日期?

How to read the receive date of mail my Gmail account using Java?

我需要开发一个 Java 连接到我的 gmail 帐户的程序,对于每封邮件 'x',它应该 system.out.println 邮件 x 的接收日期。

我在 javax.mail 库中找到了一个教程,但我无法 system.out.println 每封电子邮件的接收日期。

我使用了以下代码,但正如您在下面看到的输出,它不打印接收日期:它只打印字符串 null。

你能帮我实现我的目标吗?

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Test;

import static java.lang.Math.log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;


/**
 *
 * @author Andrea Caronello
 */
public class CheckingMails {

    public static final String RECEIVED_HEADER_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z";
public static final String RECEIVED_HEADER_REGEXP = "^[^;]+;(.+)$";


     public static void check(String host, String storeType, String user,
      String password) 
   {
      try {

      //create properties field
      Properties properties = new Properties();

      properties.put("mail.pop3.host", host);
      properties.put("mail.pop3.port", "995");
      properties.put("mail.pop3.starttls.enable", "true");
      Session emailSession = Session.getDefaultInstance(properties);

      //create the POP3 store object and connect with the pop server
      Store store = emailSession.getStore("pop3s");

      store.connect(host, user, password);

      //create the folder object and open it
      Folder emailFolder = store.getFolder("INBOX");
      emailFolder.open(Folder.READ_ONLY);

      // retrieve the messages from the folder in an array and print it
      Message[] messages = emailFolder.getMessages();
      System.out.println("messages.length---" + messages.length);

      for (int i = 0, n = messages.length; i < n; i++) {
         Message message = messages[i];
         System.out.println("---------------------------------");
         System.out.println("Email Number " + (i + 1));
         System.out.println("Subject: " + message.getSubject());
         System.out.println("From: " + message.getFrom()[0]);
         System.out.println("Text: " + message.getContent().toString());
         System.out.println("ReceiveDate: " + message.getReceivedDate());


      }

      //close the store and folder objects
      emailFolder.close(false);
      store.close();

      } catch (NoSuchProviderException e) {
         e.printStackTrace();
      } catch (MessagingException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {

      String host = "pop.gmail.com";// change accordingly
      String mailStoreType = "pop3";
      String username = "myGmailAccount@gmail.com";// change accordingly
      String password = "myPassword";// change accordingly

      check(host, mailStoreType, username, password);

}

   public Date resolveReceivedDate(MimeMessage message) throws MessagingException {
    if (message.getReceivedDate() != null) {
        return message.getReceivedDate();
    }
    String[] receivedHeaders = message.getHeader("Received");
    if (receivedHeaders == null) {
        return (Calendar.getInstance().getTime());
    }
    SimpleDateFormat sdf = new SimpleDateFormat(RECEIVED_HEADER_DATE_FORMAT);
    Date finalDate = Calendar.getInstance().getTime();
    finalDate.setTime(0l);
    boolean found = false;
    for (String receivedHeader : receivedHeaders) {
        Pattern pattern = Pattern.compile(RECEIVED_HEADER_REGEXP);
        Matcher matcher = pattern.matcher(receivedHeader);
        if (matcher.matches()) {
            String regexpMatch = matcher.group(1);
            if (regexpMatch != null) {
                regexpMatch = regexpMatch.trim();
                try {
                    Date parsedDate = sdf.parse(regexpMatch);
                    //LogMF.debug(log, "Parsed received date {0}", parsedDate);
                    if (parsedDate.after(finalDate)) {
                        //finding the first date mentioned in received header
                        finalDate = parsedDate;
                        found = true;
                    }
                } catch (Exception e) {
                    //LogMF.warn(log, "Unable to parse date string {0}", regexpMatch);
                }
            } else {
                //LogMF.warn(log, "Unable to match received date in header string {0}", receivedHeader);
            }
        }
    }

    return found ? finalDate : Calendar.getInstance().getTime();
}
}

--OUTPUT 
messages.length---4
---------------------------------
Email Number 1
Subject: Il meglio di Gmail, ovunque tu sia
From: Il team di Gmail <mail-noreply@google.com>
Text: javax.mail.internet.MimeMultipart@80b973
ReceiveDate: null
---------------------------------
Email Number 2
Subject: Tre suggerimenti per ottenere il massimo da Gmail
From: Il team di Gmail <mail-noreply@google.com>
Text: javax.mail.internet.MimeMultipart@10f3a9c
ReceiveDate: null
---------------------------------
Email Number 3
Subject: Organizza le tue email con la Posta in arrivo di Gmail
From: Il team di Gmail <mail-noreply@google.com>
Text: javax.mail.internet.MimeMultipart@d115db
ReceiveDate: null
---------------------------------
Email Number 4
Subject: test1
From: "maverick1984c@yahoo.com" <maverick1984c@yahoo.com>
Text: javax.mail.internet.MimeMultipart@f20964
ReceiveDate: null

您需要使用 imap 而不是 pop3。 POP3 协议不支持接收日期。

另请注意,您使用 pop3s 调用 getStore,但为 pop3 设置属性;这些名称必须匹配。在getStore中使用pop3然后将mail.pop3.ssl.enable设置为true更简单。但是同样,您需要在所有地方用 imap 替换 pop3 以获得接收日期。

最后,请务必修复其中任何一个 common JavaMail mistakes