Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving all unread emails using javamail with POP3 protocol

I am trying to access my gmail account and retrieve the information of all unread emails from that.

I have written my code after referring many links. I am giving a few links for reference.

Send & Receive emails through a GMail account using Java

Java Code to Receive Mail using JavaMailAPI

To test my code, I created one Gmail account. So I received 4 messages in that from Gmail. I run my application after checking number of mails. That showed correct result. 4 unread mails. All the infomation was being displayed (e.g. date, sender, content, subject, etc.)

Then I logged in to my new account, read one of the emails and rerun my application. Now the count of unread message should have been 3, but it displays "No. of Unread Messages : 0"

I am copying the code here.

public class MailReader  {      Folder inbox;      // Constructor of the calss.      public MailReader() {         System.out.println("Inside MailReader()...");         final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";          /* Set the mail properties */          Properties props = System.getProperties();         // Set manual Properties         props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);         props.setProperty("mail.pop3.socketFactory.fallback", "false");         props.setProperty("mail.pop3.port", "995");         props.setProperty("mail.pop3.socketFactory.port", "995");         props.put("mail.pop3.host", "pop.gmail.com");          try          {              /* Create the session and get the store for read the mail. */              Session session = Session.getDefaultInstance(                     System.getProperties(), null);              Store store = session.getStore("pop3");              store.connect("pop.gmail.com", 995, "[email protected]",                     "paasword");              /* Mention the folder name which you want to read. */              // inbox = store.getDefaultFolder();             // inbox = inbox.getFolder("INBOX");             inbox = store.getFolder("INBOX");              /* Open the inbox using store. */              inbox.open(Folder.READ_ONLY);              /* Get the messages which is unread in the Inbox */              Message messages[] = inbox.search(new FlagTerm(new Flags(                     Flags.Flag.SEEN), false));             System.out.println("No. of Unread Messages : " + messages.length);              /* Use a suitable FetchProfile */             FetchProfile fp = new FetchProfile();             fp.add(FetchProfile.Item.ENVELOPE);              fp.add(FetchProfile.Item.CONTENT_INFO);              inbox.fetch(messages, fp);              try              {                  printAllMessages(messages);                  inbox.close(true);                 store.close();              }              catch (Exception ex)              {                 System.out.println("Exception arise at the time of read mail");                  ex.printStackTrace();              }          }          catch (MessagingException e)         {             System.out.println("Exception while connecting to server: "                     + e.getLocalizedMessage());             e.printStackTrace();             System.exit(2);         }      }      public void printAllMessages(Message[] msgs) throws Exception     {         for (int i = 0; i < msgs.length; i++)         {              System.out.println("MESSAGE #" + (i + 1) + ":");              printEnvelope(msgs[i]);         }      }      public void printEnvelope(Message message) throws Exception      {          Address[] a;          // FROM          if ((a = message.getFrom()) != null) {             for (int j = 0; j < a.length; j++) {                 System.out.println("FROM: " + a[j].toString());             }         }         // TO         if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {             for (int j = 0; j < a.length; j++) {                 System.out.println("TO: " + a[j].toString());             }         }         String subject = message.getSubject();          Date receivedDate = message.getReceivedDate();         Date sentDate = message.getSentDate(); // receivedDate is returning                                                 // null. So used getSentDate()          String content = message.getContent().toString();         System.out.println("Subject : " + subject);         if (receivedDate != null) {             System.out.println("Received Date : " + receivedDate.toString());         }         System.out.println("Sent Date : " + sentDate.toString());         System.out.println("Content : " + content);          getContent(message);      }      public void getContent(Message msg)      {         try {             String contentType = msg.getContentType();             System.out.println("Content Type : " + contentType);             Multipart mp = (Multipart) msg.getContent();             int count = mp.getCount();             for (int i = 0; i < count; i++) {                 dumpPart(mp.getBodyPart(i));             }         } catch (Exception ex) {             System.out.println("Exception arise at get Content");             ex.printStackTrace();         }     }      public void dumpPart(Part p) throws Exception {         // Dump input stream ..         InputStream is = p.getInputStream();         // If "is" is not already buffered, wrap a BufferedInputStream         // around it.         if (!(is instanceof BufferedInputStream)) {             is = new BufferedInputStream(is);         }         int c;         System.out.println("Message : ");         while ((c = is.read()) != -1) {             System.out.write(c);         }     }      public static void main(String args[]) {         new MailReader();     } } 

I searched on google, but I found that you should use Flags.Flag.SEEN to read unread emails. But thats not showing correct results in my case.

Can someone point out where I might be doing some mistake?

If you need whole code, I can edit my post.

Note: I edited my question to include whole code instead of snippet I had posted earlier.

like image 730
MysticMagicϡ Avatar asked Oct 30 '12 10:10

MysticMagicϡ


People also ask

Is there a way to open all unopened emails?

You can use advanced search operators to select messages in other folders or unread messages in every folder. For example, to select all unread messages in your Important folder, type "label:important is:unread" into the search field. To select all unread messages in all folders, type "is:unread".

Which protocol is 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.

How do you handle thousands of unread emails?

Set up a temporary folder for all those unread emails. Set deadlines to slog through the folder of back email. At the same time, ensure your clean new inbox is empty at the end of each day.

What is the easiest way to view all unread emails in your entire email box?

Search across all folders for unread messages At the top of your Inbox, click in the Search Current Mailbox box. Type isread:no and then click Enter or click the Unread button in the Refine group on the ribbon.


1 Answers

Your code should work. You can also use the Folder.getUnreadMessageCount() method if all you want is the count.

JavaMail can only tell you what Gmail tells it. Perhaps Gmail thinks that all those messages have been read? Perhaps the Gmail web interface is marking those messages read? Perhaps you have another application monitoring the folder for new messages?

Try reading an unread message with JavaMail and see if the count changes.

You might find it useful to turn on session debugging so you can see the actual IMAP responses that Gmail is returning; see the JavaMail FAQ.

like image 195
Bill Shannon Avatar answered Oct 05 '22 16:10

Bill Shannon