Search code examples
javaiojakarta-mail

Attach large files in javamail in base64


Currently I am attaching files (small) in mail as follows:

byte[] byteArray = IOUtils.toByteArray(new FileInputStream(file)); 

MimeBodyPart messageBodyPart = new PreencodedMimeBodyPart("base64");
String contentType = "application/octet-stream";
String base64Content = new String(Base64.encodeBase64(byteArray));

messageBodyPart.setContent(base64Content, contentType);       
messageBodyPart.setFileName(MimeUtility.encodeText(attachment.getFileName(),
                                            CharEncoding.UTF_8, null));
messageBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(messageBodyPart);

But reading the file to a byte[] at a time won't work for large files. But at the end I want to put attachments in base64 encoded string in email. So how can I tackle large files in attachment here?


Solution

  • Use MimeBodyPart.attachFile:

    messageBodyPart.attachFile(file, "application/octet-stream", "base64");
    

    The file won't be read into memory, it will be encoded "on the fly" as the message is sent.