Please Help me.
My problem is, I am generate(create) csv file using printwriter object to write some data into csv file and at a time attach this csv file into email. When my code is execute csv file is generate successfully and i received email with attachment csv file but csv content is not readable format.
So please help me how can i do?
public void SendMail(HttpServletRequest req, HttpServletResponse resp) throws MessagingException, IOException {
String filename = "Testcsv.csv";
resp.setHeader("Content-Type", "text/csv");
resp.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
PrintWriter fw = ((ServletResponse) resp).getWriter();
fw.append("#");
fw.append(',');
fw.append("Product code");
fw.append(',');
fw.append("Product");
fw.append('\n');
fw.append("1");
fw.append(',');
fw.append("12345");
fw.append(',');
fw.append("testing");
fw.append('\n');
fw.flush();
fw.close();
String csvFile = fw.toString();
String host = "smtp.gmail.com";
//String host = "localhost";
String from = "emailaddress";
String toAddress = "emailaddress";
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(csvFile.getBytes(),"text/csv")));
messageBodyPart.setFileName("testcsv.csv");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
try {
Transport.send(message);
System.out.println("Mail Sent Successfully");
} catch (SendFailedException sfe) {
System.out.println(sfe);
}
}