4

我试图通过 Java 应用程序发送一封带有 excel 文件作为附件的邮件,而不实际创建文件。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);            
4

6 回答 6

27

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

任何电子表格文件都具有完全不同的二进制结构。它需要有一个Workbook,WorksheetsRowsCell数据;并且您的文本文件中显然缺少它们。这就是为什么它不能按您期望的方式工作。

下面介绍如何使用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");
于 2013-05-31T07:20:05.507 回答
3

如果您编写一个 txt 文件,您将获得一个文本文件,将您的内容类型更改为 excel 不会自动将基于选项卡的文本文件转换为 excel 文件。

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

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

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

于 2013-05-31T06:53:19.730 回答
0

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

    // 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);
于 2013-05-31T07:02:15.270 回答
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()
于 2013-05-31T06:44:04.990 回答
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";

    }
于 2019-09-13T16:07:20.307 回答
-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();
于 2013-05-31T06:56:37.893 回答