Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem in fetching receiveddate of an email with pop3 through javamail

I am trying to fetch email information of yahoo.de through javamail. I could get subject,from,to etc. but I am not able to get the received date of the email. I used getReceivedDate method and it returns null. Here is my code.. can anybody please help me how do I get the received date of the email with POP3 through javamail ?

import java.io.IOException;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

public class FolderFetchPop3 {

    public static void main(String[] args) throws MessagingException, IOException {
        Folder folder = null;
        Store store = null;

        try {
            Properties props = System.getProperties();
            props.setProperty("mail.store.protocol", "pop3");
            Session session = Session.getDefaultInstance(props, null);
            store = session.getStore("pop3");
            store.connect("pop.mail.yahoo.com","[email protected]", "password of emailid");
            folder = store.getFolder("inbox");

            if(!folder.isOpen())
            folder.open(Folder.READ_WRITE);
            Message[] messages = folder.getMessages();
            System.out.println("No of Messages : " + folder.getMessageCount());
            System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
            System.out.println(messages.length);
            for (int i=0; i < messages.length;i++) {
                System.out.println("*****************************************************************************");
                System.out.println("MESSAGE " + (i + 1) + ":");
                Message msg =  messages[i];
                //System.out.println(msg.getMessageNumber());
                System.out.println("Subject: " + msg.getSubject());
                System.out.println("From: " + msg.getFrom()[0]);
                System.out.println("To: "+msg.getAllRecipients()[0]);
                System.out.println("Date: "+msg.getReceivedDate());
                System.out.println("Size: "+msg.getSize());
            }
        } finally {
            if (folder != null && folder.isOpen()) { folder.close(true); }
            if (store != null) { store.close(); }
        }
    }
}
like image 291
user523956 Avatar asked May 27 '11 11:05

user523956


People also ask

Which protocol used to receive the messages in JavaMail?

IMAP: Acronym for Internet Message Access Protocol. It is an advanced protocol for receiving messages. It provides support for multiple mailbox for each user, in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060.

Is JavaMail deprecated?

The App Engine Mail API (which also supports JavaMail) has already been deprecated. Instead, GCP recommends to use a third-party mail provider such as: SendGrid. Mailgun.


2 Answers

Check out the Java Mail API FAQ:

Q: Why does getReceivedDate() return null when using POP3?
A: The POP3 protocol does not provide information about when a message was received. It may be possible to guess at the received date by looking at some message headers such as the Received header, but this is not very reliable.

So, in order to get some information about the received date check out MimeMessage#getHeader(String name) and try to fetch the Received headers which you can try to interpret.

like image 124
dertkw Avatar answered Oct 03 '22 23:10

dertkw


I have prepared this simple received date resolver get the latest date from Received header.

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

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

Hope this helps. If you have any improvements, let me know.

Peter

like image 37
shimon001 Avatar answered Oct 03 '22 22:10

shimon001