4

I have a base64 encoded string which is posted using JSON into a Spring form.

data:image/png;base64,iVBORw0KGg......etc

I want to add this image as an attachment to an email. Attaching the file works fine, but it is just adding the base64 string as the attachment.

I am using the following code to create the attachment part.

private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {

    if (fileName == null || fileContent == null) {
        return null;
    }

    LOG.debug("addAttachment()");

    MimeBodyPart filePart = new MimeBodyPart();

    String data = fileContent;
    DataSource ds;
    ds = new ByteArrayDataSource(data.getBytes(), "image/*");

    // "image/*"
    filePart.setDataHandler(new DataHandler(ds));
    filePart.setFileName(fileName);

    LOG.debug("addAttachment success !");

    return filePart;

}

I also tried

 ds = new ByteArrayDataSource(data, "image/*");

How can I convert the base64 string into a proper image file using the ByteArrayDataSource ?

Coen Damen
  • 2,009
  • 5
  • 29
  • 51

5 Answers5

9

To avoid decoding and re-encoding you can use the javax.mail.internet.PreencodedMimeBodyPart to load your base64 string and attach the PreencodedMimeBodyPart to your message.

    private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {
        if (fileName == null || fileContent == null) {
            return null;
        }

        LOG.debug("addAttachment()");
        MimeBodyPart filePart = new PreencodedMimeBodyPart("base64");
        filePart.setContent(fileContent, "image/*");
        LOG.debug("addAttachment success !");
        return filePart;
    }

Otherwise, you can use the javax.mail.internet.MimeUtility::decode to wrap the input stream used with your data source but this will decode and re-encode the given data.

    private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {
        if (fileName == null || fileContent == null) {
            return null;
        }

        LOG.debug("addAttachment()");
        MimeBodyPart filePart = new MimeBodyPart();

        String data = fileContent;
        DataSource ds;  //Assuming fileContent was encoded as UTF-8.
        InputStream in = new ByteArrayInputStream(data.getBytes("UTF-8"));
        try {
            in = MimeUtility.decode(in, "base64");
            try {
                ds = new ByteArrayDataSource(in , "image/*");
            } finally {
                in.close();
            }
        } catch (IOException ioe) {
            throw new MessagingException(fileName, ioe);
        }

        // "image/*"
        filePart.setDataHandler(new DataHandler(ds));
        filePart.setFileName(fileName);

        LOG.debug("addAttachment success !");
        return filePart;
    }
jmehrens
  • 10,580
  • 1
  • 38
  • 47
8

You'll hav to use a Base64-decoder first. With Java 8 you could do:

byte[] imgBytes = Base64.getDecoder().decode(base64String);

With older java-versions you'll have to use some library like apache commons-codec or something - there's lots of those around.

piet.t
  • 11,718
  • 21
  • 43
  • 52
1

i encounter the same issue and I was able to fix it using this code:

//you have to parse the data first to remove "data:image/png;base64" before you can use the decodeBase64(data).

byte[] imgBytes = Base64.decodeBase64(data);
ByteArrayDataSource dSource = new ByteArrayDataSource(imgBytes, "image/*");
arn-arn
  • 1,328
  • 1
  • 21
  • 31
1
 // v = data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA........................
String body = v.replace("data:image/png;base64","");                                    
MimeBodyPart filePart = new PreencodedMimeBodyPart("base64");
filePart.setFileName("screenshot.png");
//This is Needed if you want to show as an html element in the page
filePart.setHeader("Content-ID", "<screenshot>");
filePart.setText(body);
message.getMimeMultipart().addBodyPart(filePart);
  • Welcome to Stack Overflow! Please try to provide a nice description about how your solution works. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) Thanks – Rajesh Pandya Nov 27 '18 at 08:19
0

With the answer of @jmehrens I was able to attach a file, but they couldn't be opened. Turned out you need to set the datatype seperately and remove it from the given fileContent String:

{
   String dataType = StringUtils.substringBetween(file, "data:", ";base64,"); // extract data type (dataType = "image/png") 
base64EncodedFileContent = fileContent.replaceFirst("data:.*;base64,", ""); // remove prefix from fileContent String (base64EncodedFileContent = "iVBORw0KGg......etc"

    MimeBodyPart filePart = new PreencodedMimeBodyPart("base64");
    filePart.setContent(base64EncodedFileContent, dataType);
    filePart.setFileName(fileName);

    return filePart;
 }
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
coriefe
  • 1
  • 1