Reputation: 111
I want to persist mails in a database. To test it, I try to generate some test MimeMessage objects with and without attachments. I add the attachments like this:
MimeMessage message = new MimeMessage(Session.getDefaultInstance(props, null));
Multipart multipart = new MimeMultiPart();
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.attachFile("./files/test.txt");
bodyPart.setFileName("test.txt");
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
message.saveChanges();
Now I want to serialize this MimeMessage with its writeTo(OutputStream)
method. That call results in a FileNotFoundException:
java.io.FileNotFoundException: ./files/test.txt: open failed: ENOENT (No such file or directory)
It seems like the writeTo()
-Method is searching for the attached files. Shouldn't the files already be contained inside the MimeMessage-Object, through the attachFile()
-call in my test data generator? Do I have to do something with the MimeMessage-Object to be able to serialize it like that?
Upvotes: 0
Views: 1299
Reputation: 1892
Try using a File
object, where you can check if that file exists.
private static BodyPart createAttachment(filepath) {
File file = new File(filepath);
if (file.exists()) {
DataSource source = new FileDataSource(file);
DataHandler handler = new DataHandler(source);
BodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(handler);
attachment.setFileName(file.getName());
return attachment;
}
return null; // or throw exception
}
I noticed that you're providing a relative path to a file (starting with a dot "."). That only works if the file is in the same directory (or a subdirectory in your case) where your application is executing from. Try using an absolute path instead.
Upvotes: 1