Source Code : JavaMail Attachment Download
JavaMail Attachment Download
I'm having troubles downloading a simple jpg attachment from a Gmail Message.
It only seems to download 251 bytes and stops. I'm using the JavaMail API.
Code below:
public boolean downloadAttachment(File file, Message m, int partNumber) {
try {
Multipart mp = null;
Object content = m.getContent();
// check to see if it has any attachments
if(content instanceof Multipart){
mp = (Multipart) content;
} else {
System.out.println("Download attachment failed. Message is not multipart");
return false;
}
BodyPart bp = mp.getBodyPart(partNumber);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
BufferedInputStream is = new BufferedInputStream(bp.getInputStream());
int bytesRead;
while((bytesRead = is.read()) != -1) {
bos.write(bytesRead);
}
bos.flush();
bos.close();
is.close();
} catch (Exception e) {
System.out.println("File: " + file + "failed to download");
e.printStackTrace();
return false;
}
return true;
}