簡體   English   中英

具有7BIT內容傳輸編碼的Javamail解析電子郵件正文

[英]Javamail Parsing Email Body with 7BIT Content-Transfer-Encoding

我一直在執行一項功能,以讀取電子郵件文件。 如果文件具有附件,請返回附件名稱。 現在,我正在使用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位Content-Transfer-Encoding時,bodyPart.getFileName()會生成NullPointerException。 當電子郵件為7位Content-Transfer-Encoding時,有什么方法可以獲取附件名稱? 對不起,我的英語不好。

編輯:這是關於我的測試文件的一些信息。 (X-Mailer:Emacs 21.3 / Mule 5.0(SAKAKI)上的Mew 2.2版); (MIME版本:1.0):(內容類型:多部分/混合); (內容傳輸編碼:7位)

如果我的答案不起作用,請顯示堆棧跟蹤。

使用Session ,因為唯一可能是null。

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

並非所有附件都有文件名。 您需要處理這種情況。

而且您不需要解碼文件名

您可以通過以下方式處理“附件沒有名稱”的情況:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM