简体   繁体   中英

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;
}

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.

I think that you have not flushed and closed ZipOutputStream . Try to call zos.flush(); zos.close() zos.flush(); zos.close() . I hope this will help.

If not try to extract byte array from your ByteArrayOutputStream , save it into file and open with zip-enable tool. It is just for debugging to be sure that your ZIP is OK and is not corrupted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM