POI 不以附件形式发送 xls 文件,以字符串形式发送

Posted

技术标签:

【中文标题】POI 不以附件形式发送 xls 文件,以字符串形式发送【英文标题】:POI not sending xls file as attachment , sending as string 【发布时间】:2013-07-17 08:54:04 【问题描述】:

我的一个初级代码没有将 excel 文件作为附件发送。它正在发送文件,如

--------=_Part_0_2066339629.1374147892060 内容类型:文本/纯文本; name="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx" 内容传输编码:base64 内容处置:附件; filename="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"

UEsDBBQACAAIANqJ8kIAAAAAAAAAAAAAAAAAAAAAAAAZG9jUHJvcHMvY29yZS54bWytkV1LwzAUhu/7 K0Lu2yTr1BHaDlEGguLADsW7kB7bYvNBEu3892bdrCheennyPu/D4aRY79WA3sH53ugSs4xiBFqa ptdtiXf1Jl3hdZUkhTQOts5YcKEHj2JL+xJ3IVhOiJcdKOGzGOuYvBinRIija4kV8lW0QBaUnhMF QTQiCHKwpXbW4aOPS/vvykbOSvvmhknQSAIDKNDBE5Yx8s0GcMr/WZiSmdz7fqbGcczGfOLiRow8 3d0+TMunvfZBaAm4ShAqTnYuHYgADYoOHj4slPgrecyvrusNrhaU5Sm9SNmqZowvl/yMPhfkV//k

函数如下

          public void sendSeviceabilityMail(List<OctpinSaveBean> datalist)
                 throws MessagingException 
          Session session = null;
          Map<String, String> utilsMap = ApplicationBean.utilsProperties;
          if (utilsMap == null || utilsMap.size() == 0)
                 utilsMap = ApplicationBean.getUtilsPropertyFileValues();
          smtpHost = utilsMap.get("SMTPHost");
          to = utilsMap.get("To");
          try 
                 if (smtpHost != null && to != null) 

                       Date date = new Date();
                       XSSFWorkbook updateDataBook = 
                       updatedServiceabilityExcel(datalist);
                       Properties props = System.getProperties();
                       props.put("mail.smtp.host", smtpHost);
                       props.put("To", to);
                       session = Session.getInstance(props, null);
                       String str = "strstr";
                       Multipart multipart = new MimeMultipart();
                       BodyPart messageBodyPart1 = new MimeBodyPart();
                       messageBodyPart1.setContent(str, "text/html");
                       BodyPart messageBodyPart = new MimeBodyPart();
                       ByteArrayOutputStream baos = new ByteArrayOutputStream();
                       updateDataBook.write(baos);
                       byte[] bytes = baos.toByteArray();
                       DataSource ds = new ByteArrayDataSource(bytes,  
                        "application/vnd.ms-excel");
                       DataHandler dh = new DataHandler(ds);
                       messageBodyPart.setDataHandler(dh);
                       String fileName = "Service_Change_Alert_" + date+".xlsx";
                       messageBodyPart.setFileName(fileName);
                       messageBodyPart.setHeader("Content-disposition", "attachment; 
                        filename=\"" + fileName + "\"");
                       multipart.addBodyPart(messageBodyPart1);
                       multipart.addBodyPart(messageBodyPart);
                       if (to != null && to.length() > 0) 
                              MimeMessage msg = new MimeMessage(session);
                              msg.setFrom(new InternetAddress("tech_noida 
                       <tech_noida@xyz.com>"));
                              String[] toArray = to.split(",");
                              InternetAddress[] address = new 
                          InternetAddress[toArray.length];
                              for (int i = 0; i < toArray.length; i++) 
                                     address[i] = new InternetAddress(toArray[i]);
                              
                              msg.setRecipients(Message.RecipientType.TO, address);
                              msg.setSubject("Updated Serviceability Alert!!!");
                              msg.setContent(multipart);
                              msg.setSentDate(date);
                              try 
                                     Transport.send(msg);
                                     logger.info("Mail has been sent about the        updated               serviceability alert to :" + to);
                               catch (Exception e1) 
                                     e1.printStackTrace();
                              
                       
                 
           catch (Exception e) 
                 e.printStackTrace();
          

   

【问题讨论】:

您可以使用文件名new SimpleDateFormat("yyyy-MM-dd_HH:mm").format(date)。此外还有setDisposition 甚至setFileName 谢谢,这是一个 jar miss match 问题 :) 【参考方案1】:

问题与 POI 无关,而与 JavaMail 相关(加上不同的电子邮件客户端处理规范和格式错误的电子邮件的方式)。试试这个:

Multipart multipart = new MimeMultipart();

MimeBodyPart html = new MimeBodyPart();
// Use actual html not "strstr"
html.setContent("<html><body><h1>Hi</h1></body></html>", "text/html");
multipart.addBodyPart(html);

// ...

// Joop Eggen suggestion to avoid spaces in the file name
String fileName = "Service_Change_Alert_" 
     + new SimpleDateFormat("yyyy-MM-dd_HH:mm").format(date) + ".xlsx"; 

ByteArrayOutputStream baos = new ByteArrayOutputStream();
updateDataBook.write(baos);
byte[] poiBytes = baos.toByteArray();  
// Can be followed by the DataSource / DataHandler stuff if you really need it

MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(filename);
attachment.setContent(poiBytes, "application/vnd.ms-excel");
//attachment.setDataHandler(dh);
attachment.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(attachment);

更新:

另外不要忘记在发送消息之前调用saveChanges 来更新标头。

msg.saveChanges(); 

更多详情请参阅this answer。

【讨论】:

以上是关于POI 不以附件形式发送 xls 文件,以字符串形式发送的主要内容,如果未能解决你的问题,请参考以下文章

javaMail直接发送附件,无须生成临时文件

Apache POI 4.0.1版本写入普通Excel文件(兼容 xls 和 xlsx)

如果 java 以“content-disposition”、“attachment;filename=FileName.xls”的形式发送响应,如何通过 ajax 在现有窗口中下载文件

Python选择多个本地文件以附件发送到Email

如何在 zip 文件中生成 xls 文件并将其发送到电子邮件以在那里下载 - groovy [关闭]

以邮件附件的形式发送测试报告