Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the full email from GMail using JavaMail

I am making use of javamail and I am having trouble getting the HTML from my gmail emails. I have the following:

Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "[email protected]", "password");
System.out.println(store);

Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message); // com.sun.mail.imap.IMAPInputStream@cec0c5

The above all works fine but I can't print or get the actual HTML or Text email. I just get some sort of InputStream, how do I deal with this easily to get the raw HTML of the email?

I also tried looping through the message but that didn't get me very far:

Message message[] = inbox.getMessages();

    for (int i=0, n=message.length; i<n; i++) {
       System.out.println(i + ": " + message[i].getFrom()[0] 
         + "\t" + message[i].getSubject());
       String content = message[i].getContent().toString();
       if (content.length() > 200) 
    content = content.substring(0, 600);
       System.out.print(content);

}

Thanks all for any hlep.

like image 574
Abs Avatar asked Dec 09 '22 08:12

Abs


1 Answers

The issue is that the data you get is typically the raw data for a mime/multipart stream. You need to do something like this:

for(Message message:messages) {
  if(javax.mail.Multipart.class.isInstance(message)){
    Multipart parts = (Multipart)msg.getContent(), innerPart;
    int i;
    for(i=0;i<parts.getCount();i++){
      javax.mail.BodyPart p = parts.getBodyPart(i);
      if("text/html".equals(p.getContentType())){
        // now you can read out the contents from p.getContent()
        // (which is typically an InputStream, but depending on your javamail
        // libraries may be something else
      }
    }
  }
}

Good luck.

like image 90
Femi Avatar answered Dec 11 '22 22:12

Femi