JavaMail BaseEncode64 Error

强颜欢笑 提交于 2019-12-19 18:56:55

问题


I'm currently developing an application which download attachment from gmail account. Right now, I got error whenever downloading zipped attachment. But, not all, some I can retrieve it without error. Here's the Exception message:

Exception in thread "main" com.sun.mail.util.DecodingException: BASE64Decoder: Error in encoded stream: needed 4 valid base64 characters but only got 1 before EOF, the 10 most recent characters were: "Q3w5ilxj2P"

FYI: I was able to download the attachment via gmail web interface.

Here's the snippet:

        Multipart multipart = (Multipart) message.getContent();

        for (int i = 0; i < multipart.getCount(); i++) {

            BodyPart bodyPart = multipart.getBodyPart(i);

            if (bodyPart.getFileName().toLowerCase().endsWith("zip") ||
                    bodyPart.getFileName().toLowerCase().endsWith("rar")) {
                InputStream is = bodyPart.getInputStream();
                File f = new File("/tmp/" + bodyPart.getFileName());
                FileOutputStream fos = new FileOutputStream(f);
                byte[] buf = new byte[bodyPart.getSize()];
                int bytesRead;
                while ((bytesRead = is.read(buf)) != -1) {
                    fos.write(buf, 0, bytesRead);
                }
                fos.close();
            }
        }
    }

Anyone have idea, how to work around this problem?


回答1:


From a list of the known limitations, bugs, issues of JavaMail:

Certain IMAP servers do not implement the IMAP Partial FETCH functionality properly. This problem typically manifests as corrupt email attachments when downloading large messages from the IMAP server. To workaround this server bug, set the "mail.imap.partialfetch" property to false. You'll have to set this property in the Properties object that you provide to your Session.

So you should just turn off partial fetch in imap session. For example:

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.partialfetch", "false");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>","<password>");

source: https://javaee.github.io/javamail/docs/api/com/sun/mail/imap/package-summary.html




回答2:


If You Are Using java mail API then add these lines while you are connectin the imap server......

Properties prop = new Properties();
prop.put("mail.imaps.partialfetch", false);
Session session = Session.getDefaultInstance(prop, null);

........ .... your code .. ......

it should work.



来源:https://stackoverflow.com/questions/1755414/javamail-baseencode64-error

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