Search code examples
javaimageemailembedjodd

How to embed images to the html body of an email using the java library Jodd Email?


At the main page of the Jodd email library http://jodd.org/doc/email.html there is a very specific example on how to use the library to embed an image (and not just simply attach it as a file) to an email you are about to send.

Unfortunately the resulting Content-Type of the part of the email that contains the image is:

Content-Type: application/octet-stream

But in order to display it correctly we need this Content-Type:

Content-Type: image/png

if you have a png image for instance.

But I cannot seem to find how to configure this inside the Jodd email library..

This is what I am seeking for. Thank you :)


Solution

  • If you followed the example from Jodd site then you embedded your files using method embedFile(). This method is a 'shortcut' method for:

    attach(new FileAttachment(file));
    

    where attach() is the central, generic method for attaching content. FileAttachment rely on javax.mail for setting the content type, probably based on extension.

    Therefore, to set content type manually, use generic attach() method. For example, embedding file like this:

    .embedFile("d:\\c.xxx")
    

    would set content type to "application/octet-stream" as it is not recognized for xxx extension. Instead, you can use the following:

    .attach(new ByteArrayAttachment(
            FileUtil.readBytes("d:\\c.xxx"), "image/png", "c.png", "c.png"))
    

    where you can manually set the content type regardless the file name. If you don't want to load file bytes, you can pass InputStream instead etc.

    Another solution (if you want to keep using embedFile) is to check your mime type settings.

    Note: since there are many combinations how to attach content (bytes, input stream, file, inline...), attach methods will be refactored in Jodd 3.4.1. in order to provide more developer friendly api. Stay tuned ;)