简体   繁体   English

创建CSV文件并作为附件发送

[英]Create csv file and send as attachment

So I'm trying to generate a csv file and then immediately send it as an attachment. 因此,我尝试生成一个csv文件,然后立即将其作为附件发送。

@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? 我认为我正在使用的库不支持它(supercsv),还有其他可以执行相同操作但在内存中的库吗? 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. 发送邮件后,您只需要删除文件即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM