在我的Java Web應用程序,我需要從我的項目資源訪問路徑圖像內並將其發送給另一個sendmail.java
類我怎麼能拍攝圖像從資源文件夾路徑誰能告訴我如何從項目資源文件夾的圖像路徑和發送給另一個類的java月食
我的圖像文件夾:
當我用下面的代碼試圖它顯示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);
}
}
謝謝
您是否試過'「/HappyBirthday.JPG」'? – SilverNak
HI,@ SilverNak,我試着用你的代碼顯示同樣的異常'javax.mail.MessagingException:發送消息時發生IOException; 嵌套的異常是: \t java.io.FileNotFoundException:\ HappyBirthday.JPG(系統找不到指定的文件)' – phani
然後你必須通過classloader讀取它。檢查@StanislavL的回答 – SilverNak