Search code examples
javascriptstringspringthymeleafemail-attachments

Add image to an email from a local path


How can I add using the path that is inside a server, an image to be included in an e-mail that is sent via Spring with Thymeleaf?

This is my controller:

final Map<String, String> inlineResources = new HashMap<String, String>();
Set<String> folderPath = new TreeSet<>();
		for (File file : files) {

			... some previous code ()			
			
			StringBuilder pathFile = new StringBuilder(config.getFileCachePath());
			pathFile.append("/").append(folder.getId()).append("/").append(certificateFile.getName());
			folderPath.add(pathCertificate);
		}
    
    String folderPathString = StringUtils.collectionToCommaDelimitedString(folderPath);
    
    inlineResources.put("img1", "/template/email/img/myImg.png");
    inlineResources.put("file", "folderPath");

And this my html email:

<!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>

In this case img1 load correct, while th:src="'cid:file'" is not load.

And in folderPath.add(pathCertificate); i have this error:

The method add(String) in the type Set is not applicable for the arguments (StringBuilder)

How can I fix the problem?


Solution

  • The solution for this problem is to use "file:":

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