2012-03-19 50 views
7

我想發送電子郵件與zip文件附件..我能夠發送pdf文件,而不使用ByteArrayOutputStream保存在物理位置。但是當我嘗試壓縮這些文件時,發送它不起作用。它給出例外非法附件。如何發送zip文件而無需在物理位置創建它?

下面是我寫的創建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; 
} 
+0

你可以添加堆棧跟蹤嗎? – 2012-03-19 07:39:59

回答

0

我認爲你沒有刷新和關閉ZipOutputStream。嘗試撥打zos.flush(); zos.close()。我希望這將有所幫助。

如果不嘗試從ByteArrayOutputStream中提取字節數組,請將其保存到文件中並使用zip-enable工具打開。這只是爲了調試,以確保您的ZIP是好的,並沒有損壞。

2

寫完每個項目後,忘記了在for循環結束時調用zos.closeEntry()。如上所述,您還沒有關閉ZipOutputStream。

我不認爲你需要調用entry.setSize()。

否則,這應該工作。

相關問題