javabytearrayoutputstream

Java Mail Attach Byte array - Sends an empty file


I am using Javax mail for sending an excel workbook which I am creating, Now I am not creating a temporary file, ratehr I am creating a ByteArrayOutputStream and trying to attach this stream as a file. This is how my file creation looks:

buildexcelreport(){
DeferredSXSSFWorkbook  workbook = new DeferredSXSSFWorkbook ();
DeferredSXSSFSheet  sheet = workbook.createSheet("test");
/* code to build the excel*/
ByteArrayOutputStream fileOut = null;
try {


            fileOut = new ByteArrayOutputStream();
            workbook.write(fileOut);


        } catch (Exception e) {
            e.printStackTrace();
        }

return  fileOut;
}

Now from another method sendMail() I am accessing the fileout and attaching it as a mimebodypart

public boolean sendMail(ByteArrayOutputStream fileout) throws IOException {


//othe rcode to build the mailer


MimeBodyPart attachmentPart = new MimeBodyPart();
            ByteArrayDataSource ds = new ByteArrayDataSource(fileout.toByteArray(), "application/vnd.ms-excel");
            attachmentPart.setDataHandler(new DataHandler(ds));
            attachmentPart.setFileName("Report.xls");

Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            multipart.addBodyPart(attachmentPart);


            message.setContent(multipart);
            Transport.send(message);
            return true;


}

But when the mail is sent, the attached file is empty, though it is an excel file with the name as Report.xls. Am I missing something here?

Attach en excel using bytearray in java


Solution

  • I Solved the issue by using

    Workbook workbook = new HSSFWorkbook();
    

    Instead of using

    DeferredSXSSFWorkbook  workbook = new DeferredSXSSFWorkbook ();