【问题标题】:Javamail Parsing Email Body with 7BIT Content-Transfer-EncodingJavamail 使用 7BIT 内容传输编码解析电子邮件正文
【发布时间】:2014-03-03 02:51:25
【问题描述】:

我一直在实现读取电子邮件文件的功能。如果文件有附件,则返回附件名称。 现在我正在使用 Javamail 库来解析电子邮件文件。这是我的代码。

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

它工作正常,但是当电子邮件文件具有 7 位内容传输编码时,bodyPart.getFileName() 会产生 NullPointerException。 当电子邮件是 7bit Content-Transfer-Encoding 时,有什么方法可以获取附件名称? 对不起我的英语不好。

已编辑:这是有关我的测试文件的一些信息。 (X-Mailer:Emacs 21.3 / Mule 5.0 (SAKAKI) 上的 Mew 2.2 版); (Mime 版本:1.0):(内容类型:多部分/混合); (内容传输编码:7bit)

【问题讨论】:

    标签: java email jakarta-mail attachment


    【解决方案1】:

    如果我的回答不起作用,请显示堆栈跟踪。

    使用Session,因为这可能是唯一的空值。

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

    【讨论】:

    • 感谢您的回答,但它不起作用。堆栈跟踪仅在 bodyPart.getFileName() 行打印 java.lang.NullPointerException。
    • bodyPart 在那里不能为 null,因此在 getFileName(或 decodeText)中必须抛出 NullPointerException。抱歉,我无法提供更多帮助。
    【解决方案2】:

    并非所有附件都有文件名。你需要处理这种情况。

    还有你don't need to decode the filename

    【讨论】:

    • 非常感谢。我将“mail.mime.decodeparameters”设置为“true”,然后问题就解决了。
    【解决方案3】:

    你可以这样处理“附件没有名字”的情况:

    字符串文件名 = (bodyPart.getFileName() == null) ? “你的文件名” : bodyPart.getFileName();

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 2016-02-19
      • 1970-01-01
      • 2020-08-06
      • 2015-07-19
      • 2012-11-03
      • 2011-08-03
      • 2013-10-29
      相关资源
      最近更新 更多