2016-10-11 35 views
0

我创建了一个使用java发送邮件的jar。我必须附带一个带有邮件的excel文件。我使用HSSF来创建工作表。但我需要用密码加密附件。我成功了。但是,当我通过Outlook直接从邮件打开附件时,它不会询问密码。当我复制到任何文件夹,然后如果我尝试打开,它正常工作。任何人都可以,请帮忙吗?作为邮件附件的密码保护excel

public static void main(final String... args) throws Exception {  

     String fname = "D:\\Mail\\Sample.xls"; 

     FileInputStream fileInput = null;  
     BufferedInputStream bufferInput = null;  
     POIFSFileSystem poiFileSystem = null;  
     FileOutputStream fileOut = null; 

     try {   

      fileInput = new FileInputStream(fname);   
      bufferInput = new BufferedInputStream(fileInput);    
      poiFileSystem = new POIFSFileSystem(bufferInput);    

      Biff8EncryptionKey.setCurrentUserPassword("secret");    
      HSSFWorkbook workbook = new HSSFWorkbook(poiFileSystem, true);    
      HSSFSheet sheet = workbook.getSheetAt(0);   

      HSSFRow row = sheet.createRow(0); 
      Cell cell = row.createCell(0); 

      cell.setCellValue("THIS WORKS!"); 

      fileOut = new FileOutputStream(fname); 
      workbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), ""); 
      workbook.write(fileOut); 

      File file = new File("D:\\Mail\\Sample.xls"); 

      FileInputStream fis = new FileInputStream(file); 
      ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
      byte[] buf = new byte[1024]; 
      try { 
       for (int readNum; (readNum = fis.read(buf)) != -1;) { 
        bos.write(buf, 0, readNum); 
        System.out.println("read " + readNum + " bytes,"); 
       } 
      } catch (IOException ex) { 
      } 
      byte[] bytes = bos.toByteArray(); 

// Code for sending mail   

     } catch (Exception ex) { 

      System.out.println(ex.getMessage());  

     } finally {   

       try {    

        bufferInput.close();  

       } catch (IOException ex) { 

        System.out.println(ex.getMessage());  

       }  

       try {    

        fileOut.close();  

       } catch (IOException ex) { 

        System.out.println(ex.getMessage());  

       } 
     }  

    } 
+0

你可以发布你写的代码来创建和密码保护的Excel,并通过电子邮件发送?没有代码,这个问题看起来非常像MS Office问题,而不是编程问题。 – walen

+0

当然...请检查它... –

+0

加密代码在哪里?对'writeProtectWorkbook()'的调用只是为工作簿设置writeprotect标志。它不加密。从doc:“用一个密码保护一个工作簿(不加密,只是设置writeprotect标志和密码。” – Axel

回答

1

方法HSSFWorkbook.writeProtectWorkbook(...)仅用于保护工作簿不被写入/修改。
如果您尝试以读取+写入模式(Windows文件夹中的默认设置)打开它,它会询问您输入密码。
但是,如果您以只读模式打开它,这是Outlook使用附件执行的操作,它将允许您查看内容,因为您无法覆盖它们,因此您不需要写入密码。
这就是您可以在Outlook中查看(但不编辑)它的原因,但不能从文件夹中打开它。

我不知道Apache POI的最新版本是否支持HSSFWorkBook的完整密码保护(快速Google搜索并不知道,但是谁知道)。

如果没有,您可以通过制作一个带有Excel的密码保护的ZIP文件并附加ZIP文件来解决此问题。