Search code examples
javaemail-attachmentsmime-messagejavax.activation

Control what DataContentHandler to use for a MimeMessage attachment?


I am creating an attachment to MimeMessage for a Tiff image with a byte array.

ByteArrayOutputStream out = new ByteArrayOutputStream();
MimeBodyPart body = new MimeBodyPart();
body.setContent(tiffByteArray, "image/tiff");
body.setDisposition("attachment");
body.setFileName(filename);
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
MimeMessage message = new MimeMessage(Session.getDefaultInstance(System.getProperties()));
message.setContent(multipart);
message.writeTo(out);
String mimeContent = out.toString();

This normally works. The image is converted to a base64 string in the message. However, at some point something on the system occurs and this piece of code starts using com.sun.xml.internal.messaging.saaj.soap.ImageDataContentHandler. This particular converted expects an java.awt.Image object as opposed to a byte array (relevant source). I get the following error:

Unable to encode the image to a stream ImageDataContentHandler requires Image object, was given object of type class [B

I can see that you can set the javax.activation.DataHandler on the javax.mail.internet.MimeMessage and in the DataHandler you can set the javax.activation.DataContentHandlerFactory, but I'm not sure what to set it to.

Is there a way to force a byte array to be converted to a base64 encoded String regardless of the mime type?


Solution

  • javax.mail provides a DataSource implementation for bytes that you can explicitly use.

    ByteArrayDataSource dataSource = new ByteArrayDataSource(tiffByteArray, "image/tiff");
    DataHandler byteDataHandler = new DataHandler(dataSource);
    body.setDataHandler(byteDataHandler);
    body.setDisposition("attachment");
    body.setFileName(filename);