发送带内嵌图片的邮件触发FileNotFound异常,请求排查问题
Hey there! Let’s dig into why you’re hitting that FileNotFound error even though your image file exists and has proper permissions. Here are actionable steps to diagnose and fix the issue:
1. Double-Check Path & Case Sensitivity
Linux filesystems are case-sensitive, so don’t overlook these details:
- Confirm the filename in your code (
Logo.png) matches the actual file exactly—even a lowercaselogo.pngwould trigger this error. - Verify every directory in
/home/tahir/sportsacademy-backend/assets/Logo.pngis spelled correctly (no typos insportsacademy-backendorassets).
2. Add Explicit File Validation
Insert a quick check in your code to confirm the file is reachable at runtime. Add this right before creating the FileDataSource:
File logoFile = new File("/home/tahir/sportsacademy-backend/assets/Logo.png"); System.out.println("File exists: " + logoFile.exists()); System.out.println("File is readable: " + logoFile.canRead());
Run your app and check the console. If either output is false, you’ll know the path is wrong or the runtime user lacks access.
3. Verify Runtime User Permissions
Even if the file has rwx permissions, the user running your Java app (e.g., Tomcat user, or the account you use to start the backend) might not have access to parent directories:
- Log in as that user and run:
cat /home/tahir/sportsacademy-backend/assets/Logo.png
If this fails, adjust directory permissions to let the user traverse them (e.g., chmod +x /home/tahir).
4. Fix Syntax Error in Your Code
Your snippet has an extra closing brace } that breaks logic. Here’s the corrected section:
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>"); // Removed extra } here multipart.addBodyPart(messageBodyPart);
Ensure this code stays properly inside your try block.
5. Rule Out Symbol Links or Filesystem Quirks
If Logo.png is a symbolic link, FileDataSource might not resolve it. Use the real file path instead—find it with:
readlink -f /home/tahir/sportsacademy-backend/assets/Logo.png
Start with the file validation check and syntax fix—those are the most likely fixes. Let me know if any of these steps resolve your issue!
内容的提问来源于stack exchange,提问作者SFAH

