How to access files present inside scr folder inside code in springboot project

Viewed 36

I am keeping a png file inside src/main/resources/imagefolder/sample.png. I am using it while sending email using javamailSender. It is working fine on my local but while creating a JAR file of the application and deploying it on dev environment(Linux Server) it is throwing "FileNotFoundException".

@Autowired   
JavaMailSender javaMailSender;

MimeMessage message = javaMailSender.createMimeMessage();
message.setFrom(//Addding the configs);
message.setRecipients(//Adding the configs);
message.setSubject(//Adding the configs);

Multipart multipart=new MimeMultipart();
MimeBodyPart messageBodyPart=new MimeBodyPart();
messageBodyPart.setContent(//html in string,"text/html");
multipart.addBodyPart(messageBodyPart);
MimeBodyPart imagePart=new MimeBodyPart();
imagePart.setHeader("Content-ID","<image>");
imagePart.setDisposition(MimeBodyPart.INLINE);
imagePart.attachFile("src/main/resources/imagefolder/sample.png");
multipart.addBodyPart(imagePart);
    
message.setContent(multipart);
    
javamailSender.send(message),

Thank you in advance.

1 Answers

The simple way is:

Resource resource = new ClassPathResource("imagefolder/sample.png");
FileInputStream file = new FileInputStream(resource.getFile());

Put it without (src/main/resources/)

Related