Search code examples
restspring-bootresourcesmicroservicesamazon-ses

How to embed images and attach files from spring boot resources folder


Not able to embed images and attach files from spring boot resources folder

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.

I am using Freemarker template to compose email and using Amazon SES to send emails.

from freemarker template

<IMG src="cid:gridEmailHeaderImage">

Code to add image

MimeBodyPart inlineImage = new MimeBodyPart();
DataSource fds = new FileDataSource(imagePath.getAbsolutePath());
inlineImage.setDataHandler(new DataHandler(fds));
inlineImage.setHeader("Content-ID", "<" + contentId + ">");
inlineImage.setFileName(fds.getName());
content.addBodyPart(inlineImage);

I am able to embed and attach files if I provide absolute path. But if provide relative path it is not working.

My folder structure

C:\workspace\service-1.0\src\main\resources\images\header.png
C:\workspace\service-1.0\src\main\resources\attachements\test-attachment-1.txt

I tried the following with no sucess

Approach 1

ServletContext context;
String path = context.getRealPath("/resources/images")+"/header.png";

It is looking for images in the following folder but the images is not available in that folder.

C:\Users\username\AppData\Local\Temp\tomcat-docbase..\resources\images/header.png

Approach 2

basePath = this.getClass().getClassLoader().getResource("/images/").getPath();

C:\workspace\service-1.0\src\main\resources\images\header.png

/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)

Approach 3

ClassPathResource file = new ClassPathResource("header.png");
String mypath = file.getFile().getAbsolutePath();

(This also didn't work)

If I place the image in images folder under resource. I am able to view the image via the following URL.

http://localhost:7075/myservice/v1/images/header.png

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.


Solution

  • Since your resources are part of your jar container, you cannot use file path but URLs provided by your classloader. Depending on whether you start it from the IDE or the deployed jar, this will be either a file://... or jar:... URL. The resource folder is not part of the spring boot structure, so you must not use it. Using a URLDataSource you can just do:

    URLDataSource source = new URLDataSource(this.getClass().getResource("/images/header.png"));