Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send zip file without creating it on physical location?

I want to send email with zip file attachment.. I m able to send pdf files without saving them on physical location using ByteArrayOutputStream. But when I try zip those file an send it its not working. It gives exception illegal attachment.

Below is the code which I have written to create zip.

private MimeBodyPart zipAttachment( List<ByteArrayOutputStream> attachmentList, List<String> reportFileNames )
{
    MimeBodyPart messageBodyPart = null;
    try
    {
        // File file = File.createTempFile( "Reports.zip",".tmp" );
        // FileOutputStream fout = new FileOutputStream(file);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(attachmentList.size());
        ZipOutputStream zos = new ZipOutputStream( bout );
        ZipEntry entry;
        for( int i = 0; i < attachmentList.size(); i++ )
        {
            ByteArrayOutputStream attachmentFile = attachmentList.get( i );
            byte[] bytes = attachmentFile.toByteArray();
            entry = new ZipEntry( reportFileNames.get( i ) );
            entry.setSize( bytes.length );
            zos.putNextEntry( entry );
            zos.write( bytes );
        }
        messageBodyPart = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource( bout.toByteArray(), "application/zip" );
        messageBodyPart.setDataHandler( new DataHandler( source ) );
        messageBodyPart.setFileName( "Reports.zip" );

    }
    catch( Exception e )
    {
        // TODO: handle exception            
    }
    return messageBodyPart;
}
like image 552
DMS Avatar asked Mar 19 '12 07:03

DMS


1 Answers

You forgot to call zos.closeEntry() after each item is written, at the end of your for loop. And as noted, you haven't closed your ZipOutputStream.

I don't think you need to call entry.setSize(), either.

Otherwise, this should work.

like image 112
Jamie Avatar answered Oct 05 '22 06:10

Jamie