So I'm trying to generate a csv file and then immediately send it as an attachment.
@Async
public void sendAuditEventsReportEmail(@NonNull Locale locale,
@NonNull String fileName,
@NonNull String[] contacts,
@NonNull List<AuditEventResponse> auditEventResponses) {
try {
final MimeMessageHelper message = message(true);
message.setFrom(portalProperties.getMail().getFrom());
message.setCc(contacts);
message.setSubject(messageSource.getMessage("mail.act.subject", null, locale)
+ fileName);
writeCSVFile(fileName, auditEventResponses);
message.addInline("customer-logo",
new ClassPathResource(CUSTOMER_LOGO_PATH),
PNG_MIME);
this.mailSender.send(message.getMimeMessage());
} catch (MessagingException e) {
log.error("Could not send audit report email");
}
}
private void writeCSVFile(String fileName, List<AuditEventResponse> auditEventResponses) {
ICsvBeanWriter beanWriter = null;
try {
beanWriter = new CsvBeanWriter(new FileWriter(fileName + ".csv"),
CsvPreference.STANDARD_PREFERENCE);
String[] header = {"type", "entityType", "principal", "timestamp", "data", "date"};
beanWriter.writeHeader(header);
for (AuditEventResponse auditEventResponse : auditEventResponses) {
beanWriter.write(auditEventResponse, header);
}
} catch (IOException e) {
System.err.println("Error writing the CSV file: " + e);
} finally {
if (beanWriter != null) {
try {
beanWriter.close();
} catch (IOException e) {
System.err.println("Error closing the writer: " + e);
}
}
}
}
but as you can see, I'm only creating the file (wanted to make sure it was generated correctly). Is there a way to generate the file in memory so that I can use it as an attachment in the email? I think the library I'm using doesn't support it (supercsv) are there any others that can do the same but in memory? Thanks in advance!
If you need to send an attachment, you'll have to create physically a file, so the way you are doing your program is good. You just have to delete your file after sending your mail.