Reading the full email from GMail using JavaMail

纵饮孤独 提交于 2019-11-30 05:50:28
Chris Thompson

The InputStream object contains the body of the email. You need to read the entirety of the stream to read the entire body of the message. For instance, this SO post details how to write an entire InputStream to an OutputStream such as System.out using an Apache library. That would be a good place to start as you could print the entire message body to the console. Otherwise, you'll need to use some buffers, etc, to pull the data out of the stream and put it into whatever you want to put it in. There is also this SO post that details, using the same library, how to convert an InputStream into a String.

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.

You could use IOUtils of Apache Commons or can possibly even try something along the lines of :

BufferedReader br = new BufferedReader(new InputStreamReader(daInputStream));
String oneLine = "";
while ( (oneLine = br.readLine()) !=  null )
    System.out.println(oneLine);

if you use java mail, you can use "multipart" and "bodypart" objects to go through the email message to extract the "text/plain" and "text/html" content, which are the content you want.

your could try with the MimeMessage class:

Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "myemail@gmail.com", "password");

Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
    MimeMessage im = new MimeMessage(session, message.getContent());
    im.getFrom();
    im.getMessageID();
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!