我正在使用Javamail API,我正在尝试下载附件文件,例如word文件。 问题是我在尝试读取字节并将其保存到文件时遇到base64解码异常。 我正在使用以下代码。
Stack Exception:
IOException:com.sun.mail.util.DecodingException: BASE64Decoder: Error in encoded stream: needed 4 valid base64 characters but only got 2 before EOF, the 10 most recent characters were: "AG4AAAAAAA"
JavaMail代码:
private void getAttachments(Message temp) throws IOException, MessagingException {
List<File> attachments = new ArrayList<File>();
Multipart multipart = (Multipart) temp.getContent();
System.out.println(multipart.getCount());
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
continue; // dealing with attachments only
}
InputStream is = bodyPart.getInputStream();
File f = new File("C:\\Attachments\\" + bodyPart.getFileName());
// saveFile(bodyPart.getFileName(),is);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (br.ready()) {
System.out.println(br.readLine());
}
saveFile(bodyPart.getFileName(),is);
attachments.add(f);
}
public static void saveFile(String filename,InputStream input)
{
System.out.println(filename);
try {
if (filename == null) {
//filename = File.createTempFile("VSX", ".out").getName();
return;
}
// Do no overwrite existing file
filename = "C:\\Attachments\\" + filename;
File file = new File(filename);
for (int i = 0; file.exists(); i++) {
file = new File(filename + i);
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while ((aByte = bis.read()) >=0) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
} // end of try()
catch (IOException exp) {
System.out.println("IOException:" + exp);
}
} //end of saveFile()
答案 0 :(得分:1)
您需要禁用部分提取以解决此问题。这是你如何做到的
props.setProperty("mail.imap.partialfetch", "false");
或
props.setProperty("mail.imaps.partialfetch", "false");
如果你正在使用imaps。
以下是完整的参考: JavaMail BaseEncode64 Error
答案 1 :(得分:0)
使用MimeBodyPart中的saveFile()方法。如果你真的想在输入流中将自己的停止(!)读取行转移到你的saveFile方法之前。您正在消耗部分内容,这可能会导致问题。