简体   繁体   English

具有7BIT内容传输编码的Javamail解析电子邮件正文

[英]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. 现在,我正在使用Javamail库来解析电子邮件文件。 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. 它工作正常,但是当电子邮件文件具有7位Content-Transfer-Encoding时,bodyPart.getFileName()会生成NullPointerException。 Is there any way to get attachement name when email is 7bit Content-Transfer-Encoding? 当电子邮件为7位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)); (X-Mailer:Emacs 21.3 / Mule 5.0(SAKAKI)上的Mew 2.2版); (Mime-Version:1.0):(Content-Type: Multipart/Mixed); (MIME版本:1.0):(内容类型:多部分/混合); (Content-Transfer-Encoding: 7bit) (内容传输编码:7位)

If my answer does not work, show the stack trace. 如果我的答案不起作用,请显示堆栈跟踪。

Use a Session , as that probably is the only thing being null. 使用Session ,因为唯一可能是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) ? 字符串fileName =(bodyPart.getFileName()== null) "your_filename" : bodyPart.getFileName(); “您的文件名”:bodyPart.getFileName();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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