[英]Error loading image from class path in java
我正在尝试使用以下代码通过java邮件api发送图像;
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(username +"'s Second Story Forgotten Password");
message.setFrom(new InternetAddress(EmailAddress.ADMIN.getValue()));
message.setContent(msg, "text/html");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
Multipart multipart = new MimeMultipart();
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(msg, "text/html");
multipart.addBodyPart(htmlPart);
BodyPart imgPart = new MimeBodyPart();
DataSource ds = getImage();
imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader("Content-ID", "the-img-1");
multipart.addBodyPart(imgPart);
message.setContent(multipart);
transport.connect();
transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
ds = getImage可以在下面看到
private static DataSource getImage(){
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = MailSender.class.getClassLoader();
}
DataSource ds = new FileDataSource("/VimbaEmailLogo.png");
return ds;
}
我有一个资源文件夹,其中包含我的图像,该文件夹已添加到类路径中。 我知道此操作正确完成,因为我可以从此处加载其他文件。
每次我尝试加载png并发送电子邮件时,都会出现以下错误
DEBUG SMTP: IOException while sending, closing, THROW:
java.io.FileNotFoundException: /VimbaEmailLogo.png (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at javax.activation.FileDataSource.getInputStream(FileDataSource.java:97)
at javax.activation.DataHandler.writeTo(DataHandler.java:305)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1608)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:961)
at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:553)
at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:103)
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:889)
at javax.activation.DataHandler.writeTo(DataHandler.java:317)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1608)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1849)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1196)
at com.secondstory.mailsender.MailSender.sendSimpleMessage(MailSender.java:75)
at com.secondstory.mailsender.MailSender.generateLostPasswordEmail(MailSender.java:124)
at com.secondstory.mailsender.MailSender.main(MailSender.java:149)
我是否正确加载了图像以发送电子邮件-如果没有,我该如何更改它? 谢谢
您将获得一个类加载器,但是然后尝试使用FileDataSource
对象从文件系统加载图像。 将其更改为URLDataSource
并从您从类加载器获得的URL加载图像。
private static DataSource getImage() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = MailSender.class.getClassLoader();
}
DataSource ds = new URLDataSource(classLoader.getResource("VimbaEmailLogo.png"));
return ds;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.