0

I am using Java 11. I am reading emails and retrieving their attachments using javax.mail and would like to save the attachments byte array.

So I need to convert a javax.mail.internet.MimeBodyPart (the attachment) to a byte[].

code so far:

private void savePDF(MimeBodyPart attachment, String invoiceNumber) {
    byte[] data = attachment.get....
}

More info:

When I try open the PDF, I do the following:

InputStream is = response.getStream();
byte[] bytes = IOUtils.toByteArray(is);

OutputStream output = response.getOutputStream();
fos = new BufferedOutputStream(output);
fos.write(bytes);

This works perfectly when I get the bytes from a 'MultipartFile':

byte[] bytes = multipartFile.getBytes();

However, if I try use the byes from a MimeBodyPart (email attachment), it fails:

byte[] data = attachment.getInputStream().readAllBytes();

enter image description here

More info:

I have also tried, but I get the same error:

    BASE64DecoderStream content = (BASE64DecoderStream) attachment.getContent();
    byte[] bytes = content.readAllBytes();
    bytes = Base64.decodeBase64(bytes);
Richard
  • 8,193
  • 28
  • 107
  • 228
  • I am not sure if this will work, am going to test it: `byte[] data = attachment.getInputStream().readAllBytes();` – Richard Sep 16 '21 at 09:50
  • `byte[] data = attachment.getInputStream().readAllBytes();` does not work. When I try use these bytes to open the pdf, it says it is the file has been damaged. – Richard Sep 16 '21 at 11:34

0 Answers0