【发布时间】:2016-02-10 03:42:51
【问题描述】:
我有一个用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(访问被拒绝)
【问题讨论】:
-
你得到什么错误?
-
org.apache.jasper.JasperException: java.lang.RuntimeException: javax.mail.MessagingException: 发送消息时出现IOException;嵌套异常是:java.io.FileNotFoundException: C:\Users\gro\Desktop (Access is denied)
-
错误的哪一部分你不明白?为什么您希望您的代码能够正常工作?
-
当我发送没有附件的邮件时会发生此错误。如果我没有上传文件,那么我无法发送邮件
-
阅读错误信息。您正在尝试附加一个不存在的文件。您需要更改您的代码以不这样做。
标签: java jakarta-mail