Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java邮件API-FileInputStream中的数据源_Java_Jakarta Mail_Javax.activation - Fatal编程技术网

Java邮件API-FileInputStream中的数据源

Java邮件API-FileInputStream中的数据源,java,jakarta-mail,javax.activation,Java,Jakarta Mail,Javax.activation,我正在将JavaMailAPI集成到我的Web应用程序中。我必须在html正文中嵌入图像。如何从src/main/resource目录获取图像,而不是硬编码图像路径 try { messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource("C:\\email\\logo_email.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); mes

我正在将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();
}
请找到下面的代码,我已经硬编码的图像路径

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();
}
我不想在数据源内部调用fileinputstream,请不要使用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可能无法获得正确的类加载器。应该使用线程的上下文类加载器…

现在我遇到以下错误。javax.activation.URLDataSource.getContentTypeURLDataSource.java:78java.lang.NullPointerException位于javax.activation.URLDataSource.getContentTypeURLDataSource.java:78位于javax.activation.DataHandler.getContentTypeDataHandler.java:205