In my Spring Boot app, I'm generating HTML emails with Thymeleaf. I want to include an <img>
in these emails. The image is stored at /src/main/resources/static/img/logo.png
.
I've confirmed that the image can be resolved by starting the app locally and requesting http://localhost:8080/img/logo.svg
in a browser.
To include this image in the HTML, I've tried all of the following
<img th:src="@{/img/logo.png}" />
<img th:src="@{img/logo.png}" />
<img th:src="@{~/img/logo.png}" />
- Base64 encoded image
<img src="data:image/png;base64,iVBORw0KGgoAA..." />
The outcome of each of these is:
- Throws an exception: org.thymeleaf.exceptions.TemplateProcessingException: Link base "/img/logo.svg" cannot be context relative (/...) unless the context used for executing the engine implements the org.thymeleaf.context.IWebContext interface
- Renders
<img src="img/logo.png" />
which appears in the email as a broken image - Renders
<img src="/img/logo.png" />
which appears in the email as a broken image - The image is rendered in most email clients I tested, but it's blocked by GMail, and there's no way to unblock it via the settings.
I guess that in order for the image to be rendered correctly within an email I need to provide an absolute URL, but I'm not sure how to achieve that.
Part of the problem is that it's not obvious whether an email is not being displayed because the URL is incorrect, or because the email client is blocking images.
Update
I thought this would be obvious, but evidently not: I can't use any solution which hard-codes the hostname to localhost:8080
because this is just the URL I use when running locally, and I also need this to work in other environments, e.g. prod