AnhTT
AnhTT

Reputation: 21

Javamail Parsing Email Body with 7BIT Content-Transfer-Encoding

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)

Upvotes: 0

Views: 1272

Answers (3)

Sushant Saurabh
Sushant Saurabh

Reputation: 11

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

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

Upvotes: 0

Bill Shannon
Bill Shannon

Reputation: 29971

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

And you don't need to decode the filename.

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109547

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);

Upvotes: 0

Related Questions