Add Apache POI WorkBook as an attachment to Javamail MimeMessage without writing to the file system

I'm trying to figure out how to transfer 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 to the file system.

The easiest way to do this is as follows:

 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 

This way it works, but I have to write the file to FS.

While reading related questions, I found out about ByteArrayInputStream and ByteArrayOutputStream and seemed to solve my problem (if the file does not swell to 2GB , which seems very unlikely).

I hope I explained myself, I think ByteArray threads will do the trick, by the way, any help or advice would be appreciated!

[09/29/2011] I created a very simple DataSource implementation called (guess what) ByteArrayDataSource , so I have auto-tuning of headers and Base64 encoding.

+6
source share
1 answer

One of the MimeBodyPart constructors takes a byte array (the contents of the attachment) as an argument. So just write your book in ByteArrayOutputStream , convert this stream to an array of bytes and pass this array of bytes 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())); 
+3
source

Source: https://habr.com/ru/post/898190/


All Articles