【发布时间】:2016-10-11 15:19:28
【问题描述】:
我创建了一个 jar 用于使用 java 发送邮件。我必须用邮件附加一个excel文件。我正在使用 HSSF 创建工作表。但我需要用密码加密附件。我成功了。但是当我通过 Outlook 直接从邮件中打开附件时,它不会询问密码。当我复制到任何文件夹然后尝试打开时,它可以正常工作。有人可以帮忙吗?
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());
}
}
}
【问题讨论】:
-
您能否发布您编写的用于创建和密码保护 Excel 并通过电子邮件发送的代码?如果没有代码,这个问题看起来很像 MS Office 问题,而不是编程问题。
-
当然...请检查...
-
加密的代码在哪里?对
writeProtectWorkbook()的调用只是为工作簿设置了写保护标志。它不加密。来自文档:“使用密码保护工作簿(未加密,只需设置写保护标志和密码。” -
哦,我明白了。恕我直言,POI API 在这方面真的很糟糕......
-
是的,我需要为附件设置密码,这样当接收者打开文件时,它应该要求输入密码。我尝试使用上面的代码,它工作正常,但不是当它作为邮件附件发送时
标签: java jakarta-mail