user1068151
user1068151

Reputation: 13

POI not sending xls file as attachment , sending as string

one of my junior code is not sending excel file as attachment . It is sending file like

------=_Part_0_2066339629.1374147892060 Content-Type: text/plain; name="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Service_Change_Alert_Thu Jul 18 17:14:50 IST 2013.xlsx"

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

function is following

          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 
                       <[email protected]>"));
                              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();
          }

   }

Upvotes: 0

Views: 3379

Answers (1)

Anthony Accioly
Anthony Accioly

Reputation: 22471

The problem is not related to POI, but with JavaMail (plus the way different email clients handles the specs and malformed emails). Try this:

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);

Update:

Also don't forget to call saveChanges to update the headers before sending the message.

msg.saveChanges(); 

See this answer for further details.

Upvotes: 1

Related Questions