我在使用 java 邮件下载阿拉伯语附件文件时遇到问题。
文件名总是不明确的。
问题是 Bodypart
将附件检索为非 UTF-8 字符。
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();
// getFilename always have wrong characters set
byte [] fileBytes = bodyPart.getFileName().toString().getBytes();
String filename = new String(fileBytes, "UTF-8");
File f = new File("C:\\Attachments\\" + filename);
System.out.println(f .getName());
try {
if (f == null) {
//filename = File.createTempFile("VSX", ".out").getName();
return;
}
FileOutputStream fos = new FileOutputStream(f );
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(is);
int aByte;
while ((aByte = bis.read()) >=0) {
bos.write(aByte);
}
fos.flush();
bos.flush();
bos.close();
bis.close();
fos.close();
} // end of try()
catch (IOException exp) {
System.out.println("IOException:" + exp);
}
attachments.add(f);
}
}
最佳答案
header 根据 RFC 2047 中描述的机制进行编码(它是编码字
),该机制表示 header 的一部分与 =?
?B?
?=
是字节编码部分。 B
样式,而不是 Q
样式)<编码字节>是base-64编码的。
这相当复杂。幸运的是,您可以使用静态 javax.mail.internet.MimeUtility.decodeText() 方法轻松处理此问题。这意味着您可以切换到此:
String filename = MimeUtility.decodeText(bodyPart.getFileName());
实际上,您最好也将其与下一行结合起来:
File f = new File("C:\\Attachments",
MimeUtility.decodeText(bodyPart.getFileName()));
这更好,因为与尝试手动完成这一切相比,它可以避免更多构建文件名的麻烦。 (这也意味着您可以将该文字路径名分解到某个配置位置。)
关于java - 使用 JavaMail 阅读阿拉伯语附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7783066/