添加内嵌图像到春季电子邮件

时间:2017-04-21 09:22:41

标签: spring email thymeleaf

如何使用我的PC或服务器上的本地路径添加一个图像,该图像将包含在通过Spring与Thymeleaf一起发送的电子邮件中?

这是我的controllerMail.java:

final Map<String, String> inlineResources = new HashMap<String, String>();
Set<String> folderPath = new TreeSet<>();
        for (File file : files) {
            certificateFile = file.getCertificateFile();
            String img = certificateFile.toString();
      inlineResources.put("file", img);
        }

    inlineResources.put("img1", "/template/email/img/myImg.png");

这是我的html邮件:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title th:remove="all">Title</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body style="font-family:Trebuchet MS;">

       <p>TEXT EMAIL</p>
       <img style="max-width: 100%;" th:src="'cid:img1'" />
       <img style="max-width: 100%;" th:src="'cid:file'" />
    </body>
</html>

certificateFile返回此路径:/srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg

所以我的mail.html位于/ template / email中src / main / resources中的项目中。在这种情况下img1在电子邮件上是正确的查找(它位于相同的路径/ template / email / img)但文件返回此日志错误:

资源无效:/srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg

失败的消息:javax.mail.MessagingException:发送消息时发生IOException;   嵌套异常是:     java.io.FileNotFoundException:类路径资源[/srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg]无法打开,因为它不存在

我如何解决这个问题?

虽然此文件附加到电子邮件,但它可以正常工作。

1 个答案:

答案 0 :(得分:0)

此问题的解决方案是在“pathImg”之前使用“file:”:

String pathImg = certificateFile.toString().replace('\\', '/'); inlineResources.put("img", "file:"+pathImg);
相关问题