Search code examples
smtpimapjakarta-mailattachmentlarge-files

Javamail - How to handle large attachments?


Over imap im trying to get attachments from several messages. It works fine, but if there is an attachment with about 20 mega-bytes, then it seems stuck and java is not continuing.

Here is where the problem occurs: I want to get the content of the attachment and save it into a String:

...
MimeBodyPart attachment = (MimeBodyPart) multipart.getBodyPart(1);  
if(!Part.ATTACHMENT.equalsIgnoreCase(attachment.getDisposition())) {
    log.error("Part is not an attachment!");
} else {
    log.debug("Checking " + localFile.getName() + " with " + attachment.getFileName() + ". Attachment-Size: " + (attachment.getSize()/(1024*1024)) + " mega-bytes.");
    InputStream remoteFileIs = attachment.getInputStream();
    remoteFileContent = IOUtils.toString(remoteFileIs);  //stucked here, when attachment is large
    remoteFileIs.close();
    ...
}
...

Are there any solutions to this?

Regards!


Solution

  • What does IOUtils.toString do? Since you're just giving it an InputStream, with no charset information, it can't possibly be converting the byte stream into characters properly. And whatever it's doing it may be doing it inefficiently for large data.

    You can turn on JavaMail Session debugging and see the protocol trace as it's fetching the attachment, to determine whether it's really "stuck" or just slow.

    You can also control the buffer size for fetches from the IMAP server by setting the mail.imap.fetchsize property.

    But perhaps you should question whether you really want a 20MB attachment in a String. What are you going to do with that String once you have it?