【问题标题】:How to attach Pdf file to mail如何将PDF文件附加到邮件
【发布时间】:2013-08-06 04:44:13
【问题描述】:

我正在尝试使用 java 将准备好的 pdf 文件附加到邮件中,因此我在下面尝试

String filename = "file.pdf";

 ByteArrayOutputStream bos = new ByteArrayOutputStream();
??.write(bos);

 DataSource fds = new ByteArrayDataSource(bos.toByteArray(), "application/pdf");
 MimeBodyPart mbp2 = new MimeBodyPart();            
 mbp2.setDataHandler(new DataHandler(fds));   
 mbp2.setFileName(filename); 

我不明白用什么来代替'??'。 所以请给我建议。

【问题讨论】:

    标签: java


    【解决方案1】:

    javax.mail.util.ByteArrayDataSource 在 JavaMail 1.4 中引入,以下是一些相同的指针

    如果您使用 Spring 的 JavaMail API,您可以相当轻松地完成这类事情(或者至少,就像 JavaMail API 所允许的那样容易,这并不多)。

    附件数据可以是 Spring 的任何 Resource 抽象,ByteArrayResource 只是其中之一。

    请注意,这部分 Spring API 是独立存在的,它不需要(但确实受益于)Spring 容器。

    JavaMailSenderImpl mailSender = ... instantiate and configure JavaMailSenderImpl here
    final byte[] data = .... this holds my PDF data
    
    mailSender.send(new MimeMessagePreparator() {
       public void prepare(MimeMessage mimeMessage) throws Exception {
          MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
         // set from, to, subject using helper
         helper.addAttachment("my.pdf", new ByteArrayResource(data));
       } 
    });
    

    【讨论】:

      【解决方案2】:

      请参考以下代码:

       if (arrayInputStream != null && arrayInputStream instanceof ByteArrayInputStream) {
          // create the second message part with the attachment from a OutputStrean
          MimeBodyPart attachment= new MimeBodyPart();
          ByteArrayDataSource ds = new ByteArrayDataSource(arrayInputStream, "application/pdf"); 
          attachment.setDataHandler(new DataHandler(ds));
          attachment.setFileName("Report.pdf");
          mimeMultipart.addBodyPart(attachment);
      }
      

      【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2020-11-21
      • 2019-04-19
      • 1970-01-01
      • 2014-07-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多