0

Am integrating JavaMailAPI in my webapplication. I have to embed images in the html body. How do i get the images from the src/main/resource directory instead of hard code the image path.

Please find the below code that i have hard coded the image path.

try {
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource("C:\\email\\logo_email.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<image>");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}

I want to get the images from the following code : ( src/main/resource )

ClassLoader classLoader = getClass().getClassLoader();
FileInputStream fileinputstream = new FileInputStream(new 
File(classLoader.getResource("email/logo_email.png").getFile()));

I dont have idea to call fileinputstream inside DataSource

Karthikeyan
  • 1,927
  • 6
  • 44
  • 109

1 Answers1

1

Do not use URL.getFile() as it returns the filename part of the URL...

Use URLDataSource instead of FileDataSource. Try something like this:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("email/logo_email.png");
DataSource ds = new URLDataSource(url);

Edit

In Web applications getClass().getClassLoader() might not get the correct class loader. Should use the Thread's context class loader...

Usagi Miyamoto
  • 6,196
  • 1
  • 19
  • 33
  • Now am getting below error. java.lang.NullPointerException at javax.activation.URLDataSource.getContentType(URLDataSource.java:78) – Karthikeyan Oct 22 '17 at 14:37
  • java.lang.NullPointerException at javax.activation.URLDataSource.getContentType(URLDataSource.java:78) at javax.activation.DataHandler.getContentType(DataHandler.java:205) – Karthikeyan Oct 22 '17 at 15:01