I am working on a spring boot application. In my project I am creating a .xlsx file and then i have to send via email using spring boot.
I am able to create the file using apache poi but later to send it via mail as an attachment, i should save the file somewhere in local and then move the file back in while sending it as an attachment.
Is there any way in which I can create a .xlsx file and directly send it via email, without saving it somewhere first?
For mail I am using 'org.springframework.boot:spring-boot-starter-mail'
For .xlsx I am using 'org.apache.poi', name: 'poi', version: '4.1.2' and 'org.apache.poi', name: 'poi-ooxml', version: '4.1.2'.
Source Code
XSSFWorkbook workbook = new XSSFWorkbook();
List<String> s = Arrays.asList("person","animal");
CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
int n = 1;
String source = s.get(0);
Sheet sheet = workbook.createSheet(source);
for (String i : s) {
if(!source.equalsIgnoreCase(i)) {
sheet = workbook.createSheet(i);
Row header = sheet.createRow(0);
CellStyle headerStyle = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setFontName("Arial");
font.setBold(true);
headerStyle.setFont(font);
Cell headerCell = header.createCell(0);
headerCell.setCellValue("Name");
headerCell.setCellStyle(headerStyle);
headerCell = header.createCell(1);
headerCell.setCellValue("Age");
headerCell.setCellStyle(headerStyle);
source = i;
}
Row row = sheet.createRow(n);
Cell cell = row.createCell(0);
cell.setCellValue("Udhav Mohata");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue(22);
cell.setCellStyle(style);
n++;
}
FileOutputStream outputStream = new FileOutputStream(Path_to_the_file);
workbook.write(outputStream);
workbook.close();
sendMail();
}
public void sendMail() throws MessagingException, IOException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("spidercodie@gmail.com");
helper.setTo("udhavmohata1@gmail.com");
helper.setSubject("Test Mail");
helper.setText("Hello world");
FileSystemResource file = new FileSystemResource(path_to_the_file));
helper.addAttachment("Invoice.xlsx", file);
mailSender.send(message);
}