2017-04-21 39 views
1

如何在我的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 /内容/ jpgCache /证书/ 10000/certificateName .jpg

因此,我的mail.html位于我的项目中src/main/resources/template/email中。在这种情况下,img1在电子邮件上找到正确(它位于相同路径/模板/电子邮件/ 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

你读过Spring文档?有'addInline()'方法的'MimeMessageHelper'类。 –

+0

如果我试试这个:String certificato = new ClassPathResource(certificateFile.toString()); inlineResources.put(“certificato”,certificato);我有错误键入不匹配。我如何解决问题? –

+0

你能帮我吗? dev 12:46:20 DEBUG it.project.web.SinEmailService - :log debug class path resource [/srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg]是否正确? –

回答

0

这个问题的解决方案是使用“文件”的“pathImg”前:

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