Add an Apache POI WorkBook as attachment to a Javamail's MimeMessage without writing in the filesystem
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()));
精彩评论