java send mail with attachment 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
ByteArrayOutputStream bos = new ByteArrayOutputStream();
xlsFile.write(bos);
fos.close();
DataSource fds = new ByteArrayDataSource(bos.toByteArray(), "application/vnd.ms-excel");