0
votes

I've been implementing an feature to read email file. If the file have attachment, return attachment name. Now I'm using Javamail library to parse email file. Here is my code.

    public static void parse(File file) throws Exception {
    InputStream source = new FileInputStream(file);
    MimeMessage message = new MimeMessage(null, source);
    Multipart multipart = (Multipart) message.getContent();
    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        String disposition = bodyPart.getDisposition();
        if (disposition != null
                && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            System.out.println("FileName:"
                    + MimeUtility.decodeText(bodyPart.getFileName()));
        }
    }
}

It works fine but when email file have 7bit Content-Transfer-Encoding, bodyPart.getFileName() make NullPointerException. Is there any way to get attachement name when email is 7bit Content-Transfer-Encoding? Sorry for my poor English.

Edited: Here is some info about my test file. (X-Mailer: Mew version 2.2 on Emacs 21.3 / Mule 5.0 (SAKAKI)); (Mime-Version:1.0):(Content-Type: Multipart/Mixed); (Content-Transfer-Encoding: 7bit)

3

3 Answers

0
votes

If my answer does not work, show the stack trace.

Use a Session, as that probably is the only thing being null.

Properties properties = new Properties();
Session session = Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session, source);
0
votes

Not all attachments have a filename. You need to handle that case.

And you don't need to decode the filename.

0
votes

You can handle the case of "attachments not having a name" in this way:

String fileName = (bodyPart.getFileName() == null) ? "your_filename" : bodyPart.getFileName();