Retrieve UnRead Emails from Gmail - JavaMail API + IMAP

Ali Ben Messaoud picture Ali Ben Messaoud · Mar 20, 2011 · Viewed 30.7k times · Source

Now I have created a code to retrieve unread email and read its body and then we can store or do whatever we want to do.

It is completely working but the problem is that it giving me only the body for the first mail and for the second it gives the body with html tags.

I'm using JavaMail API...

How can I do??

Thanks in advance.

Best regards, Ali

package pack1;
//import the necessary classes

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.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;

public class InboxReader {

    public static void main(String args[]) {
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
            try {
                Session session = Session.getDefaultInstance(props, null);
                Store store = session.getStore("imaps");
                store.connect("imap.gmail.com", "mail", "pass");
                System.out.println(store);

                Folder inbox = store.getFolder("Inbox");
                inbox.open(Folder.READ_ONLY);
                //Message messages[] = inbox.getMessages();
                FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
                Message messages[] = inbox.search(ft);

                int i =0;
                for(Message message:messages) 
                {

                     Multipart mp = (Multipart)messages[i].getContent();  
                     Object p = mp.getBodyPart(i).getContent();  
                     String q = p.toString();//object has the body content  
                     System.out.println(q);//prints the body  
                     System.out.println( messages[i].getSubject()+ " \n"+i);i++;
                }


                    } catch (NoSuchProviderException e) {
                        e.printStackTrace();
                        System.exit(1);
                    } catch (MessagingException e) {
                        e.printStackTrace();
                        System.exit(2);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

    }

}

The output :

a

a 
0
<div dir="ltr">b<br>
</div>

b 
1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
    at java.util.Vector.elementAt(Unknown Source)
    at javax.mail.Multipart.getBodyPart(Multipart.java:156)
    at javax.mail.internet.MimeMultipart.getBodyPart(MimeMultipart.java:258)
    at pack1.InboxReader.main(InboxReader.java:39)

Answer

dkarp picture dkarp · Mar 22, 2011

You're using the same index to get a message from your list as to get a part from that message. So you're fetching part 1 from message 1, part 2 from message 2, etc. At some point, you'll hit a message N that has fewer than N parts, and you get the ArrayIndexOutOfBoundsException.

Multipart mp = (Multipart)messages[i].getContent();  
Object p = mp.getBodyPart(i).getContent();  

Also, you're assuming that all your messages are multipart. The first time you call Message.getContent() on a non-multipart message, you'll get a ClassCastException as it'll most likely be returning you a String instead.

Multipart mp = (Multipart)messages[i].getContent();  

Similarly, you're assuming non-nested multiparts. The first time you get a message with a top-level multipart/mixed containing a multipart/alternative as its first subpart, the call to MimeBodyPart.getContent() will return another Multipart and thus p.toString() will just return a Java object identifier, not the message content you want.

Object p = mp.getBodyPart(i).getContent();  
String q = p.toString();//object has the body content  

To do it right, you need to walk the message structure and determine the "body" part you care about.