0

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

请找到下面正在尝试的代码。

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

我收到以下错误:

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)
4

1 回答 1

0

下面的代码适用于我的这个要求。

ClassLoader classLoader = getClass().getClassLoader();
FileDataSource fds = new FileDataSource(new 
File(classLoader.getResource("email/logo_email.png").getFile()));
于 2017-10-22T16:53:58.957 回答