开发者

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

开发者 https://www.devze.com 2023-04-08 18:23 出处:网络
I\'m trying to figure out how to pass a WorkBook (from the Apache POI library) \"directly\" to a MimeMessage object (from the Javamail library) as an attachment, without having to write it directly in

I'm trying to figure out how to pass a WorkBook (from the Apache POI library) "directly" to a MimeMessage object (from the Javamail library) as an attachment, without having to write it directly in the filesystem.

The simplest way to do this seems the following:

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 an开发者_StackOverflow社区d send it

This way it works but I'm forced to write down the file into the FS.

While reading the related questions I found out about ByteArrayInputStream and ByteArrayOutputStream and seemed to solve my problem (Unless the file swells up to 2GB which seems very unlikely).

I hope I explained myself, I think the ByteArray streams will do the trick, by the way any help or advice are appreciated!

[09/29/2011] I created a very simple DataSource implementation called (guess what) ByteArrayDataSource, so I have the automatic headers setup and Base64 encoding.


One of the MimeBodyPart constructors takes a byte array (the content of the attachment) as argument. So just write your workbook to a ByteArrayOutputStream, transform this stream to a byte array, and pass this byte array to the constructor:

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

精彩评论

暂无评论...
验证码 换一张
取 消