7

我目前正在开发一个从 gmail 帐户下载附件的应用程序。现在,每次下载压缩附件时都会出错。但是,不是全部,有些我可以毫无错误地检索它。这是异常消息:

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"

仅供参考:我可以通过 gmail Web 界面下载附件。

这是片段:

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

任何人都有想法,如何解决这个问题?

4

2 回答 2

11

从JavaMail的已知限制、错误和问题列表中:

某些 IMAP 服务器未正确实现 IMAP Partial FETCH 功能。从 IMAP 服务器下载大型邮件时,此问题通常表现为损坏的电子邮件附件。要解决此服务器错误,请将“mail.imap.partialfetch”属性设置为 false。您必须在提供给 Session 的 Properties 对象中设置此属性。

所以你应该在 imap 会话中关闭部分获取。例如:

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>");

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

于 2011-03-13T22:43:26.643 回答
1

如果您使用的是 java 邮件 API,请在连接 imap 服务器时添加这些行......

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

........ .... 你的代码.. ......

它应该工作。

于 2011-10-21T12:30:17.770 回答