我想发送带有 zip 文件附件的电子邮件。我可以发送 pdf 文件,而无需使用 ByteArrayOutputStream 将它们保存在物理位置。但是当我尝试压缩这些文件并发送它时它不起作用。它给出了非法附件的异常。
下面是我编写的用于创建 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;
}
您忘记在 for 循环末尾写入每个项目后调用 zos.closeEntry() 。
如前所述,您尚未关闭 ZipOutputStream。
我认为您也不需要调用entry.setSize()。
否则,这应该有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)