从虚拟文件系统到电子邮件的Java附加文件 [英] java attach file from virtual filesystem to email

查看:89
本文介绍了从虚拟文件系统到电子邮件的Java附加文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用虚拟文件系统,我想将其中的文件附加到电子邮件中.但是,MimeBodyPart对象仅使用文件,而这些文件在默认文件系统(如jimfs)上不起作用.请参阅下面的代码,当我尝试转换为文件时,在该错误消息中出现UnsupportedOperation异常.

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
}

推荐答案

由于jimfs文件不是真正文件,因此不能使用文件API.

Since jimfs files aren't really files, you can't use the File APIs.

一个简单的解决方法是使用 ByteArrayDataSource ,它将复制数据.

A simple workaround is to use ByteArrayDataSource, which will copy the data.

更好的方法是编写自己的PathDataSource,类似于

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);

这篇关于从虚拟文件系统到电子邮件的Java附加文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆