0

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

Ananya
  • 75
  • 5
  • Can you please [edit] your question and add a [mcve]? Leave out all the Excel stuff, just attach a text file. How do you check that the attachment is empty? Can you look at the email's source? The [javadoc](https://www.gnu.org/software/classpathx/javamail/javadoc/javax/mail/internet/MimeBodyPart.html) says that you must encode the attachment. Does your `DataHandler` do that? – Robert Feb 21 '23 at 21:24
  • Please provide enough code so others can better understand or reproduce the problem. – Community Feb 22 '23 at 02:55
  • Does this answer your question? [How to add attachments to email in Java using OutputStream?](https://stackoverflow.com/questions/15709823/how-to-add-attachments-to-email-in-java-using-outputstream) – life888888 Feb 22 '23 at 07:21

1 Answers1

0

I Solved the issue by using

Workbook workbook = new HSSFWorkbook();

Instead of using

DeferredSXSSFWorkbook  workbook = new DeferredSXSSFWorkbook ();
Ananya
  • 75
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 28 '23 at 03:09