将 .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 方法。
编辑:似乎文件确实缺少某些部分。所以发送或下载邮件时出现问题。