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