News Ticker

Mule email connector: Embed images in body

Main points:

  • The Mule email connector is used to send emails
  • Email bodies can contain embedded images
  • Base64 encoded image embedding not supported by most email clients

The Mule email connector

The Mule email connector provides several operations in relation to emails such as sending and receiving emails. In this post I will discuss how to embed an image in the body of an email. Read this post to learn how to configure the Mule email connector.

Embed images in the email body

To an image in the email body you must select to send the email in HTML format and use the HTML <img> tag. The image tag includes a src attribute that locates the image. It expects to receive a URL to the image. The image must be publicly accessible from the URL configured in the src attribute.

The email configuration require at least two settings: Content and ContentType. The Content field will contain the HTML code that forms the email body, see figure 1 and the ContentType should be set to text/html.

"<b>Dear friend.</b><br>This image is for you.<img src='URL TO IMAGE'/><br><b>Kind regards</b><br>Alex."

Figure 1: The email body in HTML format and include an image reference

Download the sample code from my GitHub repository.

Use base64 encoded images

Alternatively the image can be encoded to base64 and the code added as the value to the src attribute.

"<b>Dear friend.</b><br>This image is for you.<img src='data:image/png;base64, 
INSERT ENCODED IMAGE STRING'/><br><b>Kind regards</b><br>Alex."

The image encode can be done manually online using a tool like this Base64 encoder or with the DataWeave function toBase64() from the dw::core::Binaries module. In figure 2 the image is load from the classpath and encoded. The encoded image string is stored in the payload.

%dw 2.0
output application/json
import * from dw::core::Binaries
var image = readUrl("classpath://mule.png", "application/octet-stream")
---
toBase64(image)

Figure 2: Use DataWeave to Base64 encode an image

The encoded image is then concatenated to the body HTML code as shown in figure 3.

"<b>Dear friend.</b><br>This image is for you.<img src='data:image/png;base64," ++ payload ++ "'/><br><b>Kind regards</b><br>Alex."

Figure 3: Construct the email body from the encoded image String

Download the sample code from my GitHub repository.

Final thoughts

I have present two ways to embed an image in an email body. The first method reference an image that is accessible on a publically available URL, the second approach embeds the image directly in the email body as an encoded Base64 string. This approach is likely not to be acceptable for the majority of email clients and it is recommended to use the embed URL method.

Leave a Reply

Discover more from Digital Transformation and Java Video Training

Subscribe now to keep reading and get access to the full archive.

Continue reading