通过附带excel文件的java应用程序发送电子邮件 - 无法正常工作

时间:2013-05-31 06:40:25

标签: java email

我正在尝试使用excel文件作为附件通过Java应用程序发送邮件而不实际创建文件.excel文件中的数据来自数据库。 我能够发送带附件的邮件,但文件是文本(制表符分隔)格式。但我希望文件只能是Excel格式。

请帮忙......

以下是代码:

      //Here goes my DBConnection and Query code

      while(rs.next())
      {             
         for(int i=1;i<13;i++)
         {
                   //tab for each column
                   exceldata = exceldata+""+"\t";

         }
                 // new line for end of eachrow 
                exceldata = exceldata+"\n";

     } 
     String data = exceldata;
     String filename="example";

     MimeMessage msg = new MimeMessage(session);

     //TO,From and all the mail details goes here

     DataSource fds = new ByteArrayDataSource(data,"application/vnd.ms-excel");

     MimeBodyPart mbp1 = new MimeBodyPart(); 
     mbp1.setText("Hi");

     MimeBodyPart mbp2 = new MimeBodyPart();
     mbp2.setDataHandler(new DataHandler(fds));   
     mbp2.setFileName(filename);    

     Multipart mp = new MimeMultipart();   
     mp.addBodyPart(mbp1);   
     mp.addBodyPart(mbp2);   
     msg.setContent(mp);   
     msg.saveChanges();  

     // Set the Date: header  
     msg.setSentDate(new java.util.Date()); 

     Transport.send(msg);            

6 个答案:

答案 0 :(得分:16)

您需要将标签限制数据输出到Excel文件中。只是调整MIME类型不会使Excel将标签限制 文本 文件视为Excel文档。

任何电子表格文件都有不同的二进制结构。它需要有WorkbookWorksheetsRowsCell数据;它们在您的文本文件中明显丢失。这就是为什么它不按你期望的方式工作的原因。

以下是使用Apache POI创建临时excel文件以便稍后用作邮件附件的方法。

Workbook xlsFile = new HSSFWorkbook(); // create a workbook
CreationHelper helper = xlsFile.getCreationHelper();
Sheet sheet1 = xlsFile.createSheet("Sheet #1"); // add a sheet to your workbook

while(rs.next())
{
 Row row = sheet1.createRow((short)0); // create a new row in your sheet
 for(int i = 0; i < 12; i++)
 {
   row.createCell(i).setCellValue(
     helper.createRichTextString(exceldata)); // add cells to the row
 }
} 

// Write the output to a temporary excel file
FileOutputStream fos = new FileOutputStream("temp.xls");
xlsFile.write(fos);
fos.close();

// Switch to using a `FileDataSource` (instead of ByteArrayDataSource)
DataSource fds = new FileDataSource("temp.xls");

如果您不想创建临时excel文件到转储数据 ,这里是如何实现相同的

ByteArrayOutputStream bos = new ByteArrayOutputStream();
xlsFile.write(bos); // write excel data to a byte array
fos.close();

// Now use your ByteArrayDataSource as
DataSource fds = new ByteArrayDataSource(bos.toByteArray(), "application/vnd.ms-excel");

答案 1 :(得分:3)

如果您编写txt文件,则会获得文本文件,将contenttype更改为excel将不会自动将基于选项卡的文本文件转换为Excel文件。

但幸运的是有诡计。确保您的文件名以.xls结尾。大多数电子邮件程序都会尝试将其作为Excel文件打开,即使它仍然是制表符分隔的文本文件。

同样适用于命名it.csv和使用;作为分隔符。

获得实际excel文件的唯一方法是使用创建excel文件的工具,如Apache POI prject和其他几种工具。

答案 2 :(得分:0)

试试这个。这个代码适用于附件。

    public void sendMail(String receiverId) {

    try {
        // this below commented line for the HTML body text
        // MultiPartEmail htmlEmail = new HtmlEmail();
        // OR
        // HtmlEmail email = new HtmlEmail();

        MultiPartEmail email = new MultiPartEmail();
        // setting the port number
        email.setSmtpPort(getPortNumber());
        // authenticating the user
        email.setAuthenticator(new DefaultAuthenticator(getSenderID(),
                getSenderPassword()));
        // email.setDebug(true);
        email.setSSL(true);
        // setting the host name
        email.setHostName(getHostName());
        // setting the rciever id

        email.addTo(receiverId);

        // check for user enterd cc or not
        if (getCc() != null) {
            // add the cc
            email.addCc(getCc());
        }
        // check for user enterd bcc or not
        if (getBcc() != null) {
            // add the bcc
            email.addBcc(getBcc());
        }
        // setting the sender id
        email.setFrom(getSenderID());
        // setting the subject of mail
        email.setSubject(getSubject());
        // setting message body
        email.setMsg(getBody());
        // email.setHtmlMsg("<h1>"+getBody()+"</h1>");

        // checking for attachment attachment
        if (getAttachmentPath() != null) {
            // add the attachment
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(getAttachmentPath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            email.attach(attachment);
        }

        // send the email
        email.send();
        // System.out.println("Mail sent!");
    } catch (Exception e) {
        // System.out.println("Exception :: " + e);
         e.printStackTrace();
        // gl.writeWarning("Error occured in SendMail.java of sendMailWithAttachment() ");
        // gl.writeError(e);
    }
}// sendmail()

答案 3 :(得分:0)

您可以使用以下代码通过附带excel文件的java应用程序发送电子邮件。一旦你将所有内容从db写入文件,然后关闭文件阅读器并检查文件在该位置退出的位置。

    // Define message
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO,
      new InternetAddress(to));
    message.setSubject("Hello JavaMail Attachment");

    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();

    // Fill the message
    messageBodyPart.setText("Pardon Ideas");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // Part two is attachment
    messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    // Put parts in message
    message.setContent(multipart);

    // Send the message
    Transport.send(message);

答案 4 :(得分:0)

    try {

        int smtpPort = Integer.parseInt(port);
        LocalDate localDate = LocalDate.now();
        String date = DateTimeFormatter.ofPattern("yyy-MM-dd").format(localDate);

        java.util.Properties props = new java.util.Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", "" + smtpPort);
        Session session = Session.getDefaultInstance(props, null);

        Workbook xlsFile = new HSSFWorkbook(); 
        CreationHelper helper = xlsFile.getCreationHelper();
        // add a sheet to your workbook
        Sheet sheet = xlsFile.createSheet("Lb Notification Records"); 

        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("test1 header");
        header.createCell(1).setCellValue("test2 header");
        header.createCell(2).setCellValue("test3 header");

        for(int i = 0; i <json.length(); i++) {

            JSONObject jobj = json.getJSONObject(i);
            Row dataRow = sheet.createRow(i+1);
            dataRow.createCell(0).setCellValue(jobj.getString("name_1"));
            dataRow.createCell(1).setCellValue(jobj.getString("name_2"));
            dataRow.createCell(2).setCellValue(jobj.getString("name_3"));
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // write excel data to a byte array
        xlsFile.write(bos); 
        bos.close();

        String fileName = "AffectedWipVips-"+date+".xls";
        // Construct the message
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        InternetAddress[] addressTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            addressTo[i] = new InternetAddress(to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, addressTo);

        InternetAddress[] addressCC = new InternetAddress[cc.length];
        for (int i = 0; i < cc.length; i++) {
          addressCC[i] = new InternetAddress(cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, addressCC);
        message.setSubject(subject);

        // Set the email message text.
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(content, "text/html");
        // Set the email attachment file
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messagePart); 

        // Now use your ByteArrayDataSource as
        DataSource fds = new ByteArrayDataSource(bos.toByteArray(), "application/vnd.ms-excel");

        MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(fds));

        attachmentPart.setFileName(fileName);
        multipart.addBodyPart(attachmentPart);

        message.setContent(multipart);
        Transport.send(message);

        return "Success";

    }  catch (Exception e) {
        log.error("Error in sending csv attachment  email " + e);
        e.printStackTrace();
        return "Error in sending csv attachment email";

    }

答案 5 :(得分:-1)

试试这个,

Multipart multipart = new MimeMultipart();
  multipart.addBodyPart("some text");

  // Part two is attachment
  messageBodyPart = new MimeBodyPart();

  String filePath = "your file path";
 File f1 = new File(filePath);  
DataSource source = new FileDataSource(filePath);
  messageBodyPart.setDataHandler(new DataHandler(source));
 messageBodyPart.setFileName(f1.getName());
  multipart.addBodyPart(messageBodyPart);
  // Put parts in message
  m.setContent(multipart);
  //String msg="Hello Prabhakar";
  //m.setContent(msg,"text/html");
  transport.sendMessage(m,m.getAllRecipients());
  transport.close();