Akhil kumar Amarneni
Akhil kumar Amarneni

Reputation: 230

DataSource image becomes corrupted when sending a string in inline javax.mail

I am trying to send inline image in a mail through java.I have byte array so I converted byte array to string using below function.

 public static String getImgString(byte[] fileImg) throws IOException {
    String imageString = new String(fileImg,"UTF-8");
    return imageString;
}

I got an string and this string I verified through converter it displayed and image which I used.

Now I attached my image to body of mail with below code.

byte[] arr = getImageFileBytes(); // I got byte[] from this function
DataSource dataSourceImage = new ByteArrayDataSource(getImgString(arr),"image/png"");

MimeBodyPart imageBodyPart = new MimeBodyPart();
imageBodyPart.setDataHandler(new DataHandler(dataSourceImage));

I am receiving email as below.

I think there is some format I am missing in DataSource conversion or I need to add extra data:image/png;base64 to image string??

What changes I need to do to get an image that I have in String.

Thanks in advance.

enter image description here

Upvotes: 0

Views: 784

Answers (1)

Bill Shannon
Bill Shannon

Reputation: 29971

If your image data is actually in a file, you should use the attachFile method:

MimeBodyPart mbp = new MimeBodyPart();
mbp.attachFile("file.png", "image/png", "base64");

If you only have the image data in memory, you need to do something like this:

MimeBodyPart mbp = new MimeBodyPart();
ByteArrayDataSource bds = new ByteArrayDataSource(getImageFileBytes(), "image/png");
mbp.setContent(new DataHandler(bds));

Of course, if you're referencing this image from a separate html part, you'll want to make sure both are wrapped in a multipart/related part.

More information is in the JavaMail FAQ.

Upvotes: 2

Related Questions