0

我正在将 JavaMailAPI 集成到我的 web 应用程序中。我必须在 html 正文中嵌入图像。如何从 src/main/resource 目录获取图像,而不是硬编码图像路径。

请找到我对图像路径进行硬编码的以下代码。

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()));

我不知道在 DataSource 中调用 fileinputstream

4

1 回答 1

1

不要使用,因为它会返回...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' 上下文类加载器...

于 2017-10-22T14:31:20.660 回答