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

我试图通过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); 

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

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

以下是如何使用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"); 

如果你写一个txt文件你会得到一个文本文件,将你的contenttype更改为excel将不会自动将基于标签的文本文件转换为excel文件。

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

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

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

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

  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("

"+getBody()+"

"); // 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()

您可以使用以下代码通过附带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); 

尝试这个,

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