Encoded file name for attachment
Hi
I'm writing a simple email client that connects to an imap server to fetch messages and save attachment files. The server is exchange. This works perfect, but when the mail is sent from lotus notes, the exchange server encodes the filename, even if there is no strange characters!
This is the code I use to get the file:
if (!in.hasNewMessages()){
return;
}
int nrM = in.getMessageCount();
int newM = in.getNewMessageCount();
Message[] messages = in.getMessages(nrM - newM + 1, nrM);
for (int i = 0; i < messages.length; i++){
Object content = messages[i].getContent();
String subject = messages[i].getSubject();
if (contentinstanceof BASE64DecoderStream){
saveFile(messages[i]);
}elseif (contentinstanceof Multipart){
Multipart multi = (Multipart)content;
for (int j = 0; j < multi.getCount(); j++){
BodyPart part = multi.getBodyPart(j);
saveFile(part);
}
}
}
privatevoid saveFile(Part part)throws Exception{
String fileName = part.getFileName();
if (fileName !=null){
File file =new File(outFolder, fileName);
FileOutputStream fos =new FileOutputStream(file);
part.getDataHandler().writeTo(fos);
fos.close();
}
}
The fileName looks like this: =?ISO8859-1?Q?thefile.jpg?=
Is there a way to get the correct file name? Actually, it has to cover cases where the filename has strange characters also like this:
=?ISO8859-1?Q?F=E4lt=F6?=
What I have tried is this:
String newName;
if (fileName.indexOf("=?") != -1){
System.out.println(fileName);
fileName = fileName.substring(fileName.indexOf("=?") + 2, fileName.lastIndexOf("?="));
System.out.println(fileName);
StringTokenizer st =new StringTokenizer(fileName,"?");
String encodingType = st.nextToken();
System.out.println(ecodingType);
String type = st.nextToken();
System.out.println(type);
String name = st.nextToken();
System.out.println(name);
try{
String newFileName =new String(name.getBytes(), encodingType);
newName = newFileName;
}catch (UnsupportedEncodingException uee){
newName = name;
}
}
System.out.println(newName);
This is whats printed:
=?ISO8859-1?Q?F=E4lt=F6.jpg?=
ISO8859-1?Q?F=E4lt=F6.jpg
ISO8859-1
Q
F=E4lt=F6.jpg
F=E4lt=F6.jpg
I've never used new String(byte[] bytes, String charset) before, so It might be that I'm using it wrong?
Well, here's the question:
Is there a way to get the fileName correct directly through the Java mail api? If not, how can I decode the filename to the correct name?
Thanks a lot
Tobias

