我有一個函數可以用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("[email protected]"));
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);
}
任何想法如何,我可以解決這個問題?在發送消息IOException異常;:
我得到這個錯誤:
org.apache.jasper.JasperException:了java.lang.RuntimeException:javax.mail.MessagingException的 嵌套的例外是: java.io.FileNotFoundException:C:\用戶\ GRO \桌面(訪問被拒絕)
你會得到什麼錯誤? – SLaks
org.apache.jasper.JasperException:java.lang.RuntimeException:javax.mail.MessagingException:發送消息時發生IOException; 嵌套的異常是: \t java.io.FileNotFoundException:C:\ Users \ gro \ Desktop(訪問被拒絕) – Aalm
錯誤的哪部分你不明白?你爲什麼期望你的代碼工作? – SLaks