java attach file to email code example
Example 1: sending a excel in an attachment in email java
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Hello JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Pardon Ideas");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
Example 2: sending a excel in an attachment in email java
Workbook xlsFile = new HSSFWorkbook();
CreationHelper helper = xlsFile.getCreationHelper();
Sheet sheet1 = xlsFile.createSheet("Sheet #1");
while(rs.next())
{
Row row = sheet1.createRow((short)0);
for(int i = 0; i < 12; i++)
{
row.createCell(i).setCellValue(
helper.createRichTextString(exceldata));
}
}
FileOutputStream fos = new FileOutputStream("temp.xls");
xlsFile.write(fos);
fos.close();
DataSource fds = new FileDataSource("temp.xls");