我正在使用Javamail API,并且正在尝试下载附件文件,例如word文件。
问题是尝试读取字节并将其保存到文件时出现base64解码异常。
为此,我正在使用以下代码。
堆栈异常:
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()
最佳答案
您需要禁用部分提取功能才能解决此问题。这是你可以做到的
props.setProperty("mail.imap.partialfetch", "false");
要么
props.setProperty("mail.imaps.partialfetch", "false");
如果您正在使用imaps。
这里是完整的参考:
JavaMail BaseEncode64 Error
关于java - 使用Javamail从Gmail下载Word文档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7776743/