简体   繁体   中英

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)

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

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

And you don't need to decode the filename .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM