Search code examples
javamimemultipart

Java: get content of MIME multipart BodyPart


I'm trying to retrieve content of MIME multipart using BodyPart as follow

ByteArrayOutputStream baos = null;
MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(inputStream, contentType));
int count = mp.getCount();
baos = new ByteArrayOutputStream();

for (int i = 0; i < count; i++) {
    BodyPart bodyPart = mp.getBodyPart(i);
    Object content = bodyPart.getContent();
    if (content instanceof InputStream) {

         // process inputStream

     }

bodyPart.writeTo(MIMEbaos);
String attachment = MIMEbaos.toString();

}

But bodyPart.getContent() is providing the same InputStream as whole MIME message when I expect just a content (without content-type, boundaries etc) when attachment contains whole MIME multipart body section including content-type, etc.

InputStream is from

ByteArrayOutputStream baos = new ByteArrayOutputStream();
msg.writeTo(baos);

byte[] bytes = baos.toByteArray();
InputStream inputStream = new ByteArrayInputStream(bytes);

where msg is SOAPMessage MIME type as MTOM


Solution

  • I have ended up with

    ByteArrayOutputStream baos = null;
    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(inputStream, contentType));
    int count = mp.getCount();
    baos = new ByteArrayOutputStream();
    
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = mp.getBodyPart(i);
        Object content = bodyPart.getContent();
        String content = new String(read(bodyPart));
    
        String partContentType =  bodyPart.getContentType();
    }
    
    bodyPart.writeTo(MIMEbaos);
    String attachment = MIMEbaos.toString();
    
        private static byte[] read(BodyPart bodyPart) throws MessagingException, IOException
        {
            InputStream inputStream = bodyPart.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
            int data = 0;
            byte[] buffer = new byte[1024];
    
            while ((data = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, data);
            }
    
            return outputStream.toByteArray();
        }