reading body part of a mime multipart

本秂侑毒 提交于 2019-11-29 09:16:26

Yes, you have to iterate through each BodyPart to know it's type and then get the content accordingly. Here's what I used to get the content of a message. But still I am not able to get the right content for some messages.
Edited
Works better after implementing the code suggested by Bill.

    Object msgContent = messages[i].getContent();

    String content = "";             

     /* Check if content is pure text/html or in parts */                     
     if (msgContent instanceof Multipart) {

         Multipart multipart = (Multipart) msgContent;

         Log.e("BodyPart", "MultiPartCount: "+multipart.getCount());

         for (int j = 0; j < multipart.getCount(); j++) {

          BodyPart bodyPart = multipart.getBodyPart(j);

          String disposition = bodyPart.getDisposition();

          if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) { 
              System.out.println("Mail have some attachment");

              DataHandler handler = bodyPart.getDataHandler();
              System.out.println("file name : " + handler.getName());                                 
            }
          else { 
                  content = getText(bodyPart);  // the changed code         
            }
        }
     }
     else                
         content= messages[i].getContent().toString();
carbontax

This solution worked much better for me. I merely wanted to log my email message for development/testing purposes. Use the MimeMessage.writeTo(OutputStream) method.

void logMimeMessage(MimeMessage msg) throws MessagingException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        msg.writeTo(out);
    } catch (IOException e) {
        logger.catching(new MyException("Cannot log MimeMessage",e));
    }
    logger.error(out.toString());
}

Thanks to the comment by @zzzzz above, who linked to this answer JavaMail - Parsing email content, can't seem to get it to work! (Message.getContent())

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!