title: How to embed images and attach files from spring boot resources folder
body: <p>Not able to embed images and attach files from spring boot resources folder</p>
  
  <p>I have created a Restful web service using Spring Boot (Jar file and not a War file). Some of the services will send emails and some of them will send emails with attachments (Will be created dynamically). Web part (Angular) resides in Apache server which is deployed in different server.</p>
  
  <p>I am using Freemarker template to compose email and using Amazon SES to send emails. </p>
  
  <p>from freemarker template</p>
  
  <pre><code>&lt;IMG src="cid:gridEmailHeaderImage"&gt;
  </code></pre>
  
  <p><strong>Code to add image</strong></p>
  
  <pre><code>MimeBodyPart inlineImage = new MimeBodyPart();
  DataSource fds = new FileDataSource(imagePath.getAbsolutePath());
  inlineImage.setDataHandler(new DataHandler(fds));
  inlineImage.setHeader("Content-ID", "&lt;" + contentId + "&gt;");
  inlineImage.setFileName(fds.getName());
  content.addBodyPart(inlineImage);
  </code></pre>
  
  <p>I am able to embed and attach files if I provide absolute path. But if provide relative path it is not working. </p>
  
  <p><strong>My folder structure</strong></p>
  
  <pre><code>C:\workspace\service-1.0\src\main\resources\images\header.png
  C:\workspace\service-1.0\src\main\resources\attachements\test-attachment-1.txt
  </code></pre>
  
  <p>I tried the following with no sucess</p>
  
  <p><strong>Approach 1</strong></p>
  
  <pre><code>ServletContext context;
  String path = context.getRealPath("/resources/images")+"/header.png";
  </code></pre>
  
  <p>It is looking for images in the following folder but the images is not available in that folder.</p>
  
  <blockquote>
    <p>C:\Users\username\AppData\Local\Temp\tomcat-docbase..\resources\images/header.png</p>
  </blockquote>
  
  <p><strong>Approach 2</strong></p>
  
  <pre><code>basePath = this.getClass().getClassLoader().getResource("/images/").getPath();
  </code></pre>
  
  <p>C:\workspace\service-1.0\src\main\resources\images\header.png</p>
  
  <p>/C:/workspace/service-1.0/build/libs/service-1.0.jar!/BOOT-INF/classes!/images/
  (Works only from eclipse but not from command prompt java -jar build\lib\myapp.jar)</p>
  
  <p><strong>Approach 3</strong></p>
  
  <pre><code>ClassPathResource file = new ClassPathResource("header.png");
  String mypath = file.getFile().getAbsolutePath();
  </code></pre>
  
  <p>(This also didn't work)</p>
  
  <p>If I place the image in images folder under resource. I am able to view the image via the following URL.</p>
  
  <pre><code>http://localhost:7075/myservice/v1/images/header.png
  </code></pre>
  
  <p>is it fine to load images from resource folder? Will spring boot jars get exploded at runtime. What is the correct way to load images from spring boot jar file.</p>