我在使用 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);
}
}
标头根据 RFC 2047 中描述的机制进行编码(它是encoded-word
)这表示标头的一部分匹配=?
?B?
?=
是字节编码部分。 表示如何解释字节,并且(因为它是B
风格,而不是Q
style) 采用 base-64 编码。
这一切都相当复杂。幸运的是,您可以通过使用 static 轻松处理这个问题javax.mail.internet.MimeUtility.decodeText()
方法。这意味着你可以切换到这个:
String filename = MimeUtility.decodeText(bodyPart.getFileName());
实际上,你最好也将其与下一行结合起来:
File f = new File("C:\\Attachments",
MimeUtility.decodeText(bodyPart.getFileName()));
这样做更好,因为与尝试手动完成这一切相比,它可以避免更多构建文件名的麻烦。 (这也意味着您可以将该文字路径名分解到某个配置位置。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)