Reputation: 2001
Am integrating JavaMailAPI in my webapplication. I have to embed images in the html body. Am trying to get the images from the src/main/resource directory instead of hard code the image path.
Please find the below code that am trying.
ClassLoader classLoader = getClass().getClassLoader();
URL url = classLoader.getResource("email/logo_email.png");
MimeMultipart multipart = new MimeMultipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<img src=\"cid:image\">" + "<H1>Dear Customer</H1>";
messageBodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(messageBodyPart);
try {
messageBodyPart = new MimeBodyPart();
DataSource fds = new URLDataSource(url);
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();
}
Am getting the below error :
java.lang.NullPointerException
at javax.activation.URLDataSource.getContentType(URLDataSource.java:78)
at javax.activation.DataHandler.getContentType(DataHandler.java:205)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1245)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1001)
at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:333)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1255)
at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2012)
at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:1980)
at javax.mail.Transport.send(Transport.java:97)
Upvotes: 0
Views: 1232
Reputation: 2001
Below code is worked for me to this requirement.
ClassLoader classLoader = getClass().getClassLoader();
FileDataSource fds = new FileDataSource(new
File(classLoader.getResource("email/logo_email.png").getFile()));
Upvotes: 0