3
votes

How can I add, using localhost or Server, an image to be included in an e-mail that is sent via Spring with Thymeleaf?

This is my 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");

And this my html mail:

<!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 return this path: /srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg

So my mail.html is located on my project in src/main/resources in /template/email. In this case img1 is correct find on email (it is located in the same path /template/email/img) but file return this log error:

Invalid resource: /srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg

Failed messages: javax.mail.MessagingException: IOException while sending message; nested exception is: java.io.FileNotFoundException: class path resource [/srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg] cannot be opened because it does not exist

How i can fix this problem?

While the attachment of this file to email it works properly.

1
Have you read Spring documentation? There is MimeMessageHelper class with addInline() method. - Slava Semushin
If i try this : String certificato = new ClassPathResource(certificateFile.toString()); inlineResources.put("certificato", certificato); i have error to type mismatch. How i can fix problem? - peppe71-19
Can you help me? dev 12:46:20 DEBUG it.project.web.SinEmailService - : log debug class path resource [/srv/dev/contents/jpgCache/certificate/10000/certificateName.jpg] is correct? - peppe71-19
If you have with full path to the file, then you should use FileSystemResource (instead of ClassPathResource). - Slava Semushin
The solution is: String pathImg = certificateFile.toString().replace('\\', '/'); inlineResources.put("img", "file:"+pathImg); - peppe71-19

1 Answers

0
votes

The solution for this problem is to use "file:" before the "pathImg":

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