views:

701

answers:

2

Now that I`ve downloaded all the messages, and store them to

Message[] temp;

How do I get the list of attachments for each of those messages to

List<File> attachments;

Note: no thirdparty libs, please, just JavaMail.

+3  A: 

See Getting attachments on the sun online training.

Alberto Zaccagni
+2  A: 

With exception handling, but here goes:

List<File> attachments = new ArrayList<File>();
for (Message message : temp) {
    Multipart multipart = (Multipart) message.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();
 File f = new File("/tmp/" + bodyPart.getFileName());
 FileOutputStream fos = new FileOutputStream(f);
 byte[] buf = new byte[4096];
 int bytesRead;
 while((bytesRead = is.read(buf))!=-1) {
     fos.write(buf, 0, bytesRead);
 }
 fos.close();
 attachments.add(f);
    }
David Rabinowitz
But wait a minute, aren`t we supposed to check if (bodyPart.getDisposition() == Part.ATTACHMENT){} before saving the file, so that it does not save the body of the email?
folone
You are correct, I've fixed my code
David Rabinowitz