我正在编写一个Java方法来发送带有附件的电子邮件。
我要将目标/结果文件夹中的文件附加到电子邮件。我无法附加电子邮件 以下是我到目前为止的内容:
public static void sendEmail() {
String to = "xyz@xyz.com";
String from = to;
String host = "mail.xyz.com";
String linkToLatestTest = getLink();
// Get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
// compose the message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject("Test results from today");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart
.setText("Hello,\nThis is an email regarding latest test");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "target/results";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("message sent successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
这是我得到的错误:
javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.FileNotFoundException: target\results (Access is denied)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1167)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.performanceTestLink.PerformanceTestLink.sendEmail
(PerformanceTestLink.java:49)
at com.performanceTestLink.PerformanceTestLink.main
(PerformanceTestLink.java:12)
Caused by: java.io.FileNotFoundException: target\results (Access is
denied)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at javax.activation.FileDataSource.getInputStream(FileDataSource.java:97)
at javax.activation.DataHandler.writeTo(DataHandler.java:305)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1485)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:865)
at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:462)
at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:103)
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:889)
at javax.activation.DataHandler.writeTo(DataHandler.java:317)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1485)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1773)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1119)
... 4 more
任何线索都将有所帮助。 预先感谢。
答案 0 :(得分:0)
target \ results看起来像是作为目标的目录,并且您正在尝试创建一个名为result的文件,该文件在该目录中没有扩展名。 更好的是,您可以按照以下步骤进行操作
/\[[A-Z]+-\d\]/
并确保文件所在的目录具有正确的访问权限