【发布时间】:2017-09-18 05:25:49
【问题描述】:
如何使用 localhost 或服务器添加要包含在通过 Spring with 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] 无法打开,因为它不存在
我该如何解决这个问题?
虽然此文件的附件可以通过电子邮件发送,但它可以正常工作。
【问题讨论】:
-
您阅读过 Spring 文档吗?有
MimeMessageHelper类和addInline()方法。 -
如果我试试这个:String certificato = new ClassPathResource(certificateFile.toString()); inlineResources.put("certificato", certificato);我有错误输入不匹配。我该如何解决问题?
-
你能帮帮我吗? dev 12:46:20 DEBUG it.project.web.SinEmailService - : 日志调试类路径资源 [/srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg] 是否正确?
-
如果你有文件的完整路径,那么你应该使用
FileSystemResource(而不是ClassPathResource)。 -
解决方法是:String pathImg = certificateFile.toString().replace('\\', '/'); inlineResources.put("img", "file:"+pathImg);