I have a mail message with only a attachment. No body part. How can I check the MIME type of that mail?
Created May 4, 2012
Michael Dailous Generally speaking, any email message that contains an attachment is encoded as a multipart/* email message. Even if there is no main "body" part, the email is still encoded as a multipart/* email message. You would process each part of the message just as you would any other multipart/* message. Here's a quick snippet of code that'll go through as many levels of multipart/* sections as available (NOTE: This is a _quick_ code snippet and does not do any error detection/correction):
// create a session // connect to the store // open the folder // get the message getPartMimeType(message.getContent()); public void getPartMimeType(Part p) { if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart)p.getContent(); for (int x = 0; x < mp.getCount(); x++) { if (mp.getBodyPart(x).isMimeType("multipart/*")) { getPartMimeType(mp.getBodyPart(x).getContent()); } else { System.out.println(mp.getBodyPart(x).getContentType()); } } } else { // you should do more granular checking of other mime-types System.out.println(p.getContentType()); } }This should print out the MIME type of each part of the email message, no matter how many multipart/* parts there are.
If you'd like to determine the MIME type of just the first attachment, you could modify the above code snippet as follows:
// create a session // connect to the store // open the folder // get the message getAttachmentMimeType(message.getContent()); public void getAttacheMimeType(Part p) { if (p.isMimeType("multipart/*")) { Multipart mp = (Multipart)p.getContent(); for (int x = 0; x < mp.getCount(); x++) { if (mp.getBodyPart(x).isMimeType("multipart/*")) { getAttachmentMimeType(mp.getBodyPart(x).getContent()); } else { if (checkAttachment(mp.getBodyPart(x).getDisposition())) { System.out.println(mp.getBodyPart(x).getContentType()); break; } } } } else { // you should do more granular checking of other mime-types if (checkAttachment(p.getDisposition())) { System.out.println(p.getContentType()); } } } public boolean checkAttachment(String disposition, String contentType) { if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) { return true; } return false; }