[英]Error when sending Mail and attachment in Java
我具有在Java中發送帶有附件的郵件的功能。 當我上傳附件時,它可以工作。 但是,問題是,如果我必須發送不帶附件的郵件,則在我發送郵件並且沒有上傳任何附件時會顯示錯誤消息。
這是我的代碼:
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String html = text;
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("abdool.latiff@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(email));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(html, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "C:/Users/gro/Desktop/"+attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
任何想法我可以解決這個問題?
我收到此錯誤:
org.apache.jasper.JasperException:java.lang.RuntimeException:javax.mail.MessagingException:發送消息時發生IOException; 嵌套的異常是:java.io.FileNotFoundException:C:\\ Users \\ gro \\ Desktop(訪問被拒絕)
它只是無法找到該文件。
我不確定在哪里設置attachment
字段。
但是,包裝將文件附加到消息的代碼片段,下面的代碼應該適合您:
if(attachment != null && attachment.length() > 0) {
messageBodyPart = new MimeBodyPart();
String filename = "C:/Users/gro/Desktop/"+attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
我不太了解您的實現,因為文件名是在代碼中設置的,沒有任何用戶交互。 我建議您稍微改變一下身體以獲得以下效果:
if(filename!=null) {
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
讓我看看是否可以理解,嘗試發送不帶附件的電子郵件時會收到此消息?
所以變量“ attachment”為空?
因此,您正在嘗試加載文件“ C:/ Users / gro / Desktop / null”?
而且您會為此得到FileNotFoundException? -.-
如果不了解“附件”是什么,將很難弄清楚您在做什么。 正如上面其他人已經提到的那樣,您需要檢查“ attachment”的值,如果該值存在(非null或File.exists()),則應執行將文件附加到電子郵件的代碼塊。
您能否對文件路徑(包括文件名)進行硬編碼並嘗試操作,我認為您的“附件”已設置為null或某些不存在的目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.