Dón*_*nal 5 thymeleaf spring-boot
在我的 Spring Boot 应用程序中,我使用 Thymeleaf 生成 HTML 电子邮件。我想<img>在这些电子邮件中包含一个。图像存储在/src/main/resources/static/img/logo.png。
我已经确认可以通过在本地启动应用程序并http://localhost:8080/img/logo.svg在浏览器中请求来解析图像。
要将这张图片包含在 HTML 中,我已经尝试了以下所有内容
<img th:src="@{/img/logo.png}" /><img th:src="@{img/logo.png}" /><img th:src="@{~/img/logo.png}" /><img src="data:image/png;base64,iVBORw0KGgoAA..." />每一个的结果是:
<img src="img/logo.png" />在电子邮件中显示为损坏的图像<img src="/img/logo.png" />在电子邮件中显示为损坏的图像我想为了在电子邮件中正确呈现图像,我需要提供绝对 URL,但我不确定如何实现。
部分问题在于,电子邮件之所以没有显示是因为 URL 不正确,还是因为电子邮件客户端阻止了图像,这一点并不明显。
我认为这很明显,但显然不是:我不能使用任何将主机名硬编码为的解决方案,localhost:8080因为这只是我在本地运行时使用的 URL,而且我还需要它在其他环境中工作,例如 prod
您引入一个声明“公共 url”的属性(例如在 中application.properties):
public_domain=http://somwhere.com\nRun Code Online (Sandbox Code Playgroud)\n使用它的方式如下:
\n<img th:src="@{|${public_domain}/img/logo.svg|}" />\nRun Code Online (Sandbox Code Playgroud)\n像这儿。
\n<img th:scr="${#httpServletRequest.scheme}+\'://\'+${#httpServletRequest.serverName}+\':\'+${#httpServletRequest.serverPort}+@{img/logo.svg}" />\nRun Code Online (Sandbox Code Playgroud)\n超酷!!(这只适用于存在 http(servlet)请求的情况,这似乎与这里无关。)
\n你永远不知道谁用任何客户端“观看”你的电子邮件(它信任任何服务器......并从中加载图像)!!?...
\n因此,在 html 电子邮件中嵌入图像是 [so] 中的一个“非常流行”的问题。
\n并应用于百里香:他们有一篇额外的文章!(还显示 img 附件..适用于 html 和文本(没有图像;()!!!;)
\n总结一下(一旦配置了邮件和模板):
\n模板:
\n <img src="sample.png" th:src="|cid:${imageResourceName}|" />\nRun Code Online (Sandbox Code Playgroud)\n\n\nimg 元素有一个硬编码的 src 值 \xe2\x80\x94nice 用于原型设计\xe2\x80\x94,它将在运行时被替换为与附加图像文件名匹配的 cid:image.jpg 之类的内容。
\n
服务:
\nString imageResourceName = ...\nbyte[] imageBytes = ...\nString imageContentType = ...\n\n// Prepare the evaluation context\nfinal Context ctx = new Context(locale);\n...\nctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML\n\n// Prepare message using a Spring helper\nfinal MimeMessage mimeMessage = this.mailSender.createMimeMessage();\nfinal MimeMessageHelper message = ...\nmessage.set...\n\n// Create the HTML body using Thymeleaf\nfinal String htmlContent = ...\n\n// Add the inline image, referenced from the HTML code as "cid:${imageResourceName}" !!!\nfinal InputStreamSource imageSource = new ByteArrayResource(imageBytes);\nmessage.addInline(imageResourceName, imageSource, imageContentType);\n\n// Send mail ...\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
279 次 |
| 最近记录: |