try {
String fileName = p.getFileName();
String disposition = p.getDisposition();
String contentType = p.getContentType();
if (fileName == null && (disposition.equals(Part.ATTACHMENT)
|| !contentType.equals("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 version that does not yet exist
for (int i = 1; f.exists(); i++) {
String newName = fileName + " " + i;
f = new File(newName);
}
FileOutputStream out = 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 e) {
System.err.println(e);
e.printStackTrace();
}