0

I am having troubles with parsing MIME messages. I have some PCAP files with packets which contain specific attachments I want. I can retrieve full attachment from a mail, which has only a single attachment (content type: application/octet stream) not more. When I try to get multiple attachments I get only around 70% from each attachment. Is it problem with Java Mail parser or am I doing something wrong?

public ArrayList<Attachment> parseMessage() {

    ArrayList<Attachment> attachments = new ArrayList<>();

           try {



        Session s = Session.getDefaultInstance(new Properties());    

        InputStream is = new ByteArrayInputStream(parts.getBytes());    

        MimeMessage message = new MimeMessage(s, is);

             if(!message.getContentType().contains("multipart"))

            return null;

            Multipart multipart = (Multipart) message.getContent();


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

            Part part = multipart.getBodyPart(j);


            if (part.getDisposition() != null && part.getDisposition().equals("attachment") && part.getContentType().contains("application")) {


                attachments.add(new Attachment(this.searchForContent(part),part.getFileName()));

            }
        }

     //   } 


    } catch (MessagingException ex) {

    } catch (IOException ex) {

    }

   return attachments;
    }



public byte[] searchForContent(Part part) {

    InputStream is = null;

    ArrayList<Byte> list = new ArrayList<>();

    try {
        is = part.getInputStream();

        int character = 0;

        while ((character = is.read()) != -1) {

            list.add((byte) character);

        }
    } catch (Exception ex) {
    }

    byte[] bytes = new byte[list.size()];

    for (int i = 0; i < bytes.length; i++) {

        bytes[i] = list.get(i);

    }
    return bytes;
}   
Mayda
  • 1
  • 2

1 Answers1

0

A List of bytes? Yow! That's inefficient! If you really need the data in a byte array, try copying it to a ByteArrayOutputStream.

Anyway, I can't tell from the code you published how you're detecting that only 70% of the content is available. Is it possible that parts.getBytes() isn't returning all the data? How do you know? Do you perhaps have a complete test program along with a test message file that shows the problem?

What version of JavaMail are you using?

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
  • I am using version 1.5.1. and I found List of bytes useful, because I dont know the length of bytes I am going to read. I didnt write any tests, but I got the whole TCP session from pcap, so I could see that the whole Base64 encoded attachment is all right before trying to parse it using Java Mail. 70 % was just a guess. Exactly I get 491048 bytes out of 512 000 and 747519 out of 786432 bytes which is in both cases 95%. (sorry for earlier guess) Anyway in both cases it is the same percentage loss. – Mayda Apr 08 '14 at 08:14