I have a piece of code that read my inbox email. the code identify 2 kind of attachments:
1) The attached files, which are downloaded and saved to a database. This works just fine.
2) The inline attachment (I'm using an image as the attachment in my tests). The code detects this kind of attachment, but when I save them to disk the file seems to be corrupted. I checked the file properties generated and noticed that it had no basic info (pixels, height, width) with it. I think the file is not saved properly when downloaded to disk (I have tried PNG and JPG). I think the file needs to be saved with a kind of mimetype properties so i can open it properly. Any tips please? Thanks in advance.!
Here is a snip of my code:
public void procesMultiPart(Multipart content) throws SQLException {
try {
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
String downloadDirectory = "D:/Attachment/";
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println("procesMultiPart es plainText");
} else if (null != bodyPart.getDisposition() && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println("IS ATTACHMENT...");
// i save the attachment to database and is OK..
} else if (bodyPart.getDisposition() == null){
System.out.println("IS AN INLINE ATTACHMENT...");
String fileNameinline = "inline" + i + ".png";
InputStream inStream = bodyPart.getInputStream();
FileOutputStream outStream = new FileOutputStream(new File(downloadDirectory + fileNameinline), true);
byte[] tempBuffer = new byte[4096];// 4 KB
int numRead;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
inStream.close();
outStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
Thanks to everyone for help and tips. I solved the problem. This is how i did it: I notice that when read the email body (where supposes there was just the pasted image) , there was more that just the image, there was a kind of HTML too, so in other words, the body part has multiparts (2 parts in my case), so i have to process each part until find the image, so i can save it. hope this help someone else. regards.