Why does JavaMail BodyPart.getInputStream() return an empty stream when using IMAP, but not when using POP3?

匆匆过客 提交于 2019-12-24 07:06:42

问题


I have a javax.mail application that parses through emails and gets the InputStream for all application/* attachments:

private DataInputStream getAttachmentStream(Message message) throws MessagingException, IOException {
    if (message.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) message.getContent();

        for (int p = 0; p < mp.getCount(); p++) {
            BodyPart part = mp.getBodyPart(p);

            if (part.getContentType().toLowerCase().startsWith("application")) {
                InputStream is = part.getInputStream();

                DataInputStream dis = new DataInputStream(is);

                App.logger.info("Found attachment."");
                return dis;
            }
        }
    }

    App.logger.warn("No attachment found.");
    return null;
}

My problem is that even for emails that have an attachment, the resultant DataInputStream is empty. I've stepped through in the debugger, and part is definitely the correct Message part with the attachment.

I switched the protocol of my code that checks the email address to use POP3 instead of IMAP, and this code magically worked. Can anyone explain why this code works for POP3 and not for IMAP?


回答1:


It has been some time since this thread was opened, but I think the problem described in here was due to bugs in partial fetch implementation of IMAP server. As described in this link http://www.oracle.com/technetwork/java/faq-135477.html#fetch and in these notes https://javamail.java.net/docs/NOTES.txt . There is a workaround to solve it, add the following property:

props.setProperty("mail.imap.partialfetch", "false");



来源:https://stackoverflow.com/questions/25812757/why-does-javamail-bodypart-getinputstream-return-an-empty-stream-when-using-im

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!