[英]Error reading attachments from eml file using Java Mail API
将.eml文件转换为MimeMessages并将附件和嵌入式图像保存到文件的代码:
// fileList contains paths to eml files
for (File file : fileList) {
MimeMessage mail = Utility.mailFromFile(file);
if (mail == null) {
os.println("Error: " + file.getAbsolutePath()
+ " has an unsupported format.");
continue;
}
try {
MimeBodyPart bPart = (MimeBodyPart) content.getBodyPart(i);
for (int i = 0; i < content.getCount(); i++) {
BodyPart bPart = content.getBodyPart(i);
// sort out messages but include inline images
if (bPart.getFileName() == null) {
continue;
}
String savePath = outputDirectory.getAbsolutePath() + "\\" + bPart.getFileName();
File f = new File(savePath);
// generate new file name in case file already exists
f = Utility.getSaveFile(f);
bPart.saveFile(f);
}
} catch (Exception ex) {
os.println("Error: " + ex.getMessage());
continue;
}
}
这适用于大多数eml文件,但有时会出现以下异常:
Error: BASE64Decoder: Error in encoded stream: needed 4 valid base64 characters but only got 2 before EOF, the 10 most recent characters were: "GJMIX5FF\r\n"
并且保存的文件为空。 eml文件由Mozilla Thunderbird生成。 如何防止此异常发生? 附件肯定在那里,还有有效的电影/图像文件。
编辑:现在使用saveFile方法。
编辑:似乎文件确实缺少某些部分。 因此,发送或下载邮件时出现问题。
我需要查看整个消息,以查看是否确实存在base64编码错误。
您正在使用哪个版本的JavaMail? 在较早的版本中,该区域存在一些错误。
您的代码中存在一个严重错误,该错误可能与您看到的错误相关,也可能与该错误无关。 如javadocs中对Part.getSize方法的描述 ,它可能不会返回零件的确切大小。 您应该从InputStream读取数据,直到EOF。 或者更好的方法是使用MimeBodyPart.saveFile方法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.