Search code examples
javabase64mimejakarta-mail

Decode Base64 content from a MimeMultipart


I have a Base64 file into one part of my MimeMessage. I put it like this

DataSource source = new FileDataSource(new File("base64Test.bin"));
bodyPart.setDataHandler(new DataHandler(source));

Then, I want to decode it using the method BASE64DecoderStream.decode

String base64 = (String)bodyPart.getContent();
byte [] base64Decoder = BASE64DecoderStream.decode(base64.getBytes());

The problem with that is that I have always an ArrayOutOfboundexception when I use this method.

Any advice in order to solve this problem?


Solution

  • As far as I know, a Base64DecoderStream takes an InputStream, not a byte array. At a minimum, you need to change the decoding like so:

    ByteArrayInputStream contentStream = new ByteArrayInputStream(base64Content.getBytes());
    BASE64DecoderStream decodeStream = new BASE64DecoderStream(contentStream);
    int decodedByte
    while ((decodedByte = read()) != -1) {
       // handled decoded bytes
    }
    

    Perhaps autoboxing is trying to help you out, and some "intermediate" array creation is fouling the works. Or, maybe your message is just large enough that an array can't be created big enough. Or maybe you have two threads calling the static offering which is messing up internal shared buffers.