通过java发送pdf作为附件

时间:2015-05-27 15:28:09

标签: java pdf javamail

我有以下java程序,它将pdf文件作为附件发送,并且从我的本地系统读取pdf文件,然后生成一个邮件,其中附加了该pdf文件然后发送

下面是代码现在我现在有一个查询仪式,你可以在我的代码中看到该文件是从我的本地系统读取并最终被转换并存储在一个字节数组中但是当我要发送邮件它接受了 文件名为字符串 所以我只是试图发送加密的同一个文件存储在一个字节数组中 请告知我如何发送与字节数组本身相同的文件

 //  attachment part
   MimeBodyPart attachPart = new MimeBodyPart();
  String filename = "c:\\index.pdf";

String filename_src = "c:\\index.pdf";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(filename_src);
PdfStamper stamper = new PdfStamper(reader, baos);
// Do the encrypting stuff
stamper.close();
byte[] result = baos.toByteArray(); //***** encrypted file in byte array ************


//*******program to send the encrypted file as an attachment ********
//accepts string as file name want to sore the above byte array itself 
   DataSource source = new FileDataSource(filename_dest);
    attachPart.setDataHandler(new DataHandler(source));

2 个答案:

答案 0 :(得分:0)

除非您的Java邮件库(半)自动执行(例如 apache.commons.mail ),否则您必须将附件编码为 Base64 有效负载并添加适当的在通过电子邮件发送有效载荷之前的mime-type标题。

您可以参考Apache Commons Email encode attach with base64作为示例,或者参考https://community.oracle.com/thread/1592976您可以添加

 final String payload = Base64.Encoder.encodeToString(result);
 attachPart.setText(payload);
 attachPart.setHeader("Content-Type", "application/pdf"); // Use x-pdf instead for backward compatibility with old / legacy software
 attachPart.setHeader("Content-Transfer-Encoding", "base64");

答案 1 :(得分:0)

请参阅ByteArrayDataSource课程。