从Docker容器中的Springboot资源读取文件

m1m5dgzv  于 2022-11-29  发布在  Spring
关注(0)|答案(1)|浏览(267)

我正在尝试发送邮件正文中包含内联图像的邮件。当我从eclipse本地运行时,代码运行正常。但是当它被停靠并部署到Kubernetes集群时,它无法读取png文件。
我收到错误消息“java.io.FileNotFoundException:无法将类路径资源[External_Files/email_template.png]解析为绝对文件路径,因为它不驻留在文件系统中:”Project structure screen shot“文件夹中的所有文件

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setSubject(AppConstants.EMAIL_SUBJECT);
MimeMultipart multipart = new MimeMultipart(AppConstants.RELATED);
MimeBodyPart messageBodyPart = new MimeBodyPart();
String html = AppConstants.EMAIL_HTML_PART_1 + recepientName + 
AppConstants.EMAIL_HTML_PART_2
    + fromName + AppConstants.EMAIL_HTML_PART_3 + appProperties.getEmailOnboardPage()
    + AppConstants.EMAIL_HTML_PART_4 + appProperties.getEmailHelpPage()
    + AppConstants.EMAIL_HTML_PART_5;
messageBodyPart.setContent(html, AppConstants.TEXT_HTML);
multipart.addBodyPart(messageBodyPart);

MimeBodyPart messageBodyPart2 = new MimeBodyPart();
DataSource fds = new FileDataSource(ResourceUtils.getFile(src/main/resources/External_Files/email_template.png));
 messageBodyPart2.setDataHandler(new DataHandler(fds));
 messageBodyPart2.setHeader(AppConstants.CONTENT_ID, AppConstants.IMAGE_HEADER);
 multipart.addBodyPart(messageBodyPart2);

 message.setContent(multipart);
message.setHeader(AppConstants.X_PRIORITY, AppConstants.ONE);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
log.info("executing Transport.send");
Transport.send(message);

png

798qvoo8

798qvoo81#

@Indranil Halder我知道现在回答这个问题已经很晚了,但是对于其他有这个问题的人来说,找到这个问题会很有用
您可以使用ResourceLoader在Spring jar文件中查找类路径,

@Autowired
ResourceLoader resourceLoader;
Resource resource = resourceLoader.getResource("classpath:External_Files/email_template.png");

相关问题