try {
String fileName = p.getFileName();
String disposition = p.getDisposition();
String contentType = p.getContentType();
if (contentType.toLowerCase().startsWith("multipart/")) {
processMultipart((Multipart) p.getContent() );
}
else if (fileName == null
&& (Part.ATTACHMENT.equalsIgnoreCase(disposition)
|| !contentType.equalsIgnoreCase("text/plain"))) {
// pick a random file name. This requires Java 1.2 or later.
fileName = File.createTempFile("attachment", ".txt").getName();
}
if (fileName == null) { // likely inline
p.writeTo(System.out);
}
else {
File f = new File(fileName);
// find a file that does not yet exist
for (int i = 1; f.exists(); i++) {
String newName = fileName + " " + i;
f = new File(newName);
}
OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
// We can't just use p.writeTo() here because it doesn't
// decode the attachment. Instead we copy the input stream
// onto the output stream which does automatically decode
// Base-64, quoted printable, and a variety of other formats.
InputStream in = new BufferedInputStream(p.getInputStream());
int b;
while ((b = in.read()) != -1) out.write(b);
out.flush();
out.close();
in.close();
}
}
catch (Exception ex) {
System.err.println(e);
ex.printStackTrace();
}