在我的Web应用程序中集成JavaMailAPI。我必须在 html 正文中嵌入图像。如何从 src/main/资源目录获取图像,而不是对图像路径进行硬编码。
请找到我已硬编码图像路径的以下代码。
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();
}
我想从以下代码中获取图像:( src/main/resource )
ClassLoader classLoader = getClass().getClassLoader();
FileInputStream fileinputstream = new FileInputStream(new
File(classLoader.getResource("email/logo_email.png").getFile()));
我不知道在数据源中调用文件输入流
不要使用 URL.getFile()
,因为它返回URL
的文件名部分...
使用 URLDataSource
而不是 FileDataSource
。尝试这样的事情:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("email/logo_email.png");
DataSource ds = new URLDataSource(url);
编辑
在 Web 应用程序中,getClass().getClassLoader()
可能无法获得正确的类装入器。应该使用Thread
的上下文类加载器...