如何从项目资源文件夹获取图像路径并发送到java eclipse

时间:2017-08-07 12:56:00

标签: java

在我的Java Web应用程序中,我需要从我的项目资源中访问图像中的路径并将其发送到另一个sendmail.java类,如何从资源文件夹中获取图像路径,任何人都可以告诉我

我的图片文件夹:

image folder structure

当我尝试使用以下代码时,它会显示file not found error

我试过这个:

String imgpath="/resources/HappyBirthday.JPG";
SendEmail stp=new SendEmail();
stp.mail(From, To,Name,text,imgpath);

SendEmail.java:

public String mail(String From,String To,String Name,String text,String imgPath){
Properties props = new Properties();
          props.put("mail.smtp.host", "mail.com");
          props.put("mail.smtp.socketFactory.port", "465");
          props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
          props.put("mail.smtp.auth", "false");
          props.put("mail.smtp.port", "25");
          // Get the default Session object.
          Session session = Session.getDefaultInstance(props);
 try {            
             MimeMessage message = new MimeMessage(session);
             message.setFrom(new InternetAddress(From));
             message.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
             message.setSubject("Wishes!", "UTF-8");
             message.setText(text, "UTF-8");

          // first part (the html)
              BodyPart messageBodyPart = new MimeBodyPart();
              String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
              messageBodyPart.setContent(htmlText, "text/html");
              // add it

            // second part (the image)
              messageBodyPart = new MimeBodyPart();         
              DataSource fds = new FileDataSource(imgPath); //here adding image path to send mail like image and text 
              messageBodyPart.setDataHandler(new DataHandler(fds));
              messageBodyPart.setHeader("Content-ID", "<image>");           
             MimeMultipart multipart = new MimeMultipart("related");
             multipart.addBodyPart(messageBodyPart);
             message.setContent(multipart);
             // Send message
             Transport.send(message);
             System.out.println("Sent message successfully....");          
          }catch (MessagingException mex) {
             mex.printStackTrace();
             System.out.println(mex);
          }
}    

谢谢

2 个答案:

答案 0 :(得分:0)

期待文件是不正确的。如果您的代码是在jar中编译的,则该文件不可用。

改为使用

InputStream inputStream = this.getClass().getResourceAsStream("/HappyBirthday.JPG");

ByteArrayDataSource ds = new ByteArrayDataSource(inputStream, "image/jpg");

编译代码时,资源被移动到classes,并且可以在那里作为资源流而不是文件访问。

答案 1 :(得分:0)

如果您使用Maven,则应将其添加到您的pom.xml

<resources>
        <resource>
            <directory>${basedir}/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>

然后它只适用于

String imgpath="HappyBirthday.JPG";

如果我对Maven有误,我很抱歉,我仍然无法对问题发表评论