try {
// I'd prefer to test the Content-Disposition header here.
// However, too many common email clients don't use it.
String fileName = p.getFileName();
if (fileName == null) { // likely inline
p.writeTo(System.out);
}
else if (fileName != null) {
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();
}