java - 发送消息时出现 IOException - 找不到文件
问题描述
我正在发送带有内联图像的邮件,但问题是它给了我一个错误,FileNotFound
我正在使用正确的路径,但仍然会抛出错误,任何人都可以告诉我我错在哪里?
代码
public void forgotPasswordMail(String email,String token)
{
String to = email;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setSubject("Reset Password");
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
MimeMultipart multipart = new MimeMultipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = //"<img src=\"cid:image\"> " +
"<html><head><style>h1 {background-color: #FFF100;padding: 15px; text-indent: 40px;} " +
"p {text-indent: 60px;}</style></head><body><h1>Forgot password request</h1> " +
"<p> Please click on the following link to set new password</p>" +
"<p>" + frontendUrl+"resetForgottonPassword/"+token+"</p></div></body></html>";
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource(
"/home/tahir/sportsacademy-backend/assets/Logo.png");
messageBodyPart.setFileName("logo.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");}
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
并且文件也有读写权限
文件位置
解决方案
有多种原因可能导致这种情况,但我猜问题是您正在文件系统位置中查找文件,并且您的程序在根文件夹不同的 Web 上下文中运行。如果您正在制作一个 Web 应用程序,即使您在 /home 文件夹中进行开发,它也会在 servlet 容器提供的 Web 上下文中运行,或者使用嵌入的 servlet 容器从您的 IDE 中运行)。实际的文件夹结构有点不同。这是因为在共享 Web 应用程序环境中存在封装,并且每个应用程序只能访问属于它的文件(否则您可能能够修改不属于您的文件)。
因此,为了检查这一点,如果您在 Web 环境中运行,您可以通过在您的 servlet 上下文中调用 getRealPath("/") 方法来检查实际文件夹,该方法会显示实际的文件系统路径。但基本上,您需要在 Web 应用程序上下文中而不是在文件系统中使用它们的相对路径来访问资源。
推荐阅读
- python - python dataframe 3d条形图轴标签和刻度的重叠问题
- php - 我可以在 PHP 文件上 `require_once __DIR__.'/folder.file.php';`,但无法获取变量。为什么会发生这种情况?
- c++ - 在不获取 Ascii dec 值的情况下将 char 转换为 int
- reactjs - 如何使用 useState 更改嵌套对象的属性值?
- api - 每当我在颤动中运行我的程序时,我在控制台中收到此错误任何解决方案?
- gitlab - GitLab API 未列出容器注册表中的所有图像存储库
- android-studio - 如何在 Android Studio 4.1 中导出项目?
- python - HTTP 错误 404:未找到 尝试在浏览器中打开(网页抓取时)
- android - 为什么在第一个响应时调用 onResponse?
- reactjs - 使用带有 ReactTable 的查询参数