繁体   English   中英

添加Apache POI WorkBook作为Javamail的MimeMessage的附件,而无需在文件系统中写入

[英]Add an Apache POI WorkBook as attachment to a Javamail's MimeMessage without writing in the filesystem

我试图找出如何将“直接”工作WorkBook (来自Apache POI库)作为附件传递给MimeMessage对象(来自Javamail库),而不必直接在文件系统中编写它。

最简单的方法如下:

File attachmentSource = new File("tmpsource.xls");

WorkBook tmpWorkbook = new HSSFWorkBook();
//Do stuff with workbook
tmpWorkBook.write(new FileOutputStream(attachmentSource));

//Create all the Session, MimeMessage and MimeMultipart
MimeBodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(new DataHandler(new FileDataSource(attachmentSource)));
attachment.setFileName(attachmentSource.getName());

//Do stuff with the message and send it

这种方式可行,但我被迫将文件写入FS。

在阅读相关问题时,我发现了ByteArrayInputStreamByteArrayOutputStream ,似乎解决了我的问题(除非文件膨胀到2GB ,这似乎不太可能)。

我希望我自己解释一下,我认为ByteArray流可以做到这一点,顺便提一下任何帮助或建议!

[09/29/2011]我创建了一个非常简单的DataSource实现,称为(猜测是什么) ByteArrayDataSource ,所以我有自动头设置和Base64编码。

其中一个MimeBodyPart构造函数将一个字节数组(附件的内容)作为参数。 因此,只需将工作簿写入ByteArrayOutputStream ,将此流转换为字节数组,并将此字节数组传递给构造函数:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
tmpWorkBook.write(baos);
MimeBodyPart attachment = new MimeBodyPart(internetHeaders, baos.toByteArray());
// or MimeBodyPart attachment = 
//        new MimeBodyPart(new ByteArrayInputStream(baos.toByteArray()));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM