Search code examples
javajakarta-mailjavax.activation

Java Mail API - Datasource from FileInputStream


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


Solution

  • 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...