Reputation: 4701
I am using a virtual filesystem and I'd like to attach a file from it to an email. However, the MimeBodyPart object only takes Files, which don't work on a default filesystem like jimfs. See my code below, where I get an UnsupportedOperation exception when I try to convert to file.
public Email attach(Path file){
MimeBodyPart attachment = new MimeBodyPart()
attachment.attachFile(file.toFile())
attachments.add(attachment)
return this
}
Upvotes: 1
Views: 403
Reputation: 29971
Since jimfs files aren't really files, you can't use the File APIs.
A simple workaround is to use ByteArrayDataSource, which will copy the data.
A better approach would be to write your own PathDataSource that's similar to FileDataSource but uses Files.newInputStream instead of FileInputStream. Then attach the file using:
MimeBodyPart mbp = new MimeBodyPart();
mbp.setDataHandler(new DataHandler(new PathDataSource(path)));
mbp.setFileName(path.getFileName().toString());
mbp.setDisposition(Part.ATTACHMENT);
Upvotes: 3
Reputation: 110094
Whatever this MimeBodyPart
API is really ought to have an option to use a Path
so that you could just use the Jimfs file directly, but since the java.nio.file
APIs require Java 7 and don't work on Android yet many libraries unfortunately don't support Path
yet.
toFile()
can never work for a Jimfs file, or for any file that isn't on the default file system, because the File
class can only represent files on the default file system. So yeah, you'd need to copy the Jimfs file to the real file system to use this attachFile
method.
If the MimeBodyPart
API had an option for using a URL
or URI
for the attachment, you would probably be able to use that plus file.toUri()[.toURL()]
. Or if it could use, say, an InputStream
you could obviously get one of those from the file and use it instead.
Upvotes: 1