java - How to read email contents? -
i have developed simple java application reads gmail inbox mails. able read email , subject. but, unable read email contents.
when try read it, below exception:
exception msg: com.sun.mail.imap.imapinputstream cannot cast javax.mail.multipart
code:
import com.sun.mail.imap.imapfolder; import com.sun.mail.imap.imapstore; import javax.mail.address; import javax.mail.bodypart; import javax.mail.message; import javax.mail.messagingexception; import javax.mail.multipart; import javax.mail.session; import java.io.ioexception; import java.util.list; import java.util.properties; public class read_mail { static string from; public static void main(string args[]) { properties props = new properties(); props.setproperty("mail.store.protocol", "imaps"); session session = session.getdefaultinstance(props,null); imapstore imapstore = null; try { imapstore = (imapstore) session.getstore("imaps"); imapstore.connect("imap.gmail.com", "usernamexxxxx@gmail.com", "passwordxxx"); final imapfolder folder = (imapfolder) imapstore.getfolder("inbox"); folder.open(imapfolder.read_only); message[] messages = folder.getmessages(); (int = 0; < messages.length; i++) { message message = messages[i]; system.out.println("=============================="); system.out.println("email #" + (i + 1)); system.out.println("subject: " + message.getsubject()); system.out.println("from: " + message.getfrom()[0]); // system.out.println("text: " + message.getcontent()); object mp = (object) message.getcontent(); if (mp instanceof string) { string body = (string)mp; system.out.println("msg body : " + body); } else if (mp instanceof multipart) { multipart mpp = (multipart)mp; final bodypart bp = mpp.getbodypart(i); system.out.println("text: " +bp.getcontent().tostring()); } else { system.out.println("inside else"); multipart mpp = (multipart)mp; final bodypart bp = mpp.getbodypart(i); system.out.println("text: " +bp.getcontent().tostring()); } } } catch(exception e) { system.out.println("exception msg: " + e.getmessage()); } } }
it goes inside else
block , fires exception.
not sure you're asking.
in final else you're ignoring fact you've determined it's not multipart (it failed instanceof multipart) go ahead , try , cast multipart anyway. of course it's going fail.
now know imapinputstream possibility, add else-if class (or, better, inputstream) , process other stream. better yet, java ee docs stream returned if doesn't know data type, maybe that's final else.
if check stream, final else should generate error of sort.
Comments
Post a Comment