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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With