thomas
thomas

Reputation: 1271

Javamail - CSVPrinter : send email with csv attached

I want to send an email with csv attachment without having to store the csv file on the server.

I create my csv :

StringWriter sw = new StringWriter();        
try {
    CSVPrinter csvPrinter = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(
        "Année", "Mois", "Date", "Pièce", "Libellé",
        "Débit", "Crédit", "Compte", "Journal"
    ));
    for (ExportComptaAV export : exports){
        csvPrinter.printRecord(export.getAnnee().getLibelle(),
                                export.getMois().getLibelle(),
                                export.getDateMouvement().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                                export.getPiece(),
                                export.getLibelle(),
                                export.getMontantDebit().toString(),
                                export.getMontantCredit().toString(),
                                export.getNumCompte(),
                                export.getCodeJournal());
    }

} catch (IOException e) {
    e.printStackTrace();
}

And my email procedure :

MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, CharEncoding.UTF_8);
    InternetAddress ad = new InternetAddress("[email protected]");
    message.addTo(ad);
    message.setSubject(sujet);
    message.setText(content, isHtml);
    String fileName = "csvFile.csv";
    message.addAttachment(fileName,  new ByteArrayResource(...));

    javaMailSender.send(mimeMessage);
} catch (MessagingException mex) {
    throw mex;
}

So I would like to convert my CsvPrinter to a ByteArrayresource.

Is there a way to do that?

Upvotes: 0

Views: 1281

Answers (1)

Bill Shannon
Bill Shannon

Reputation: 29971

Get the String from the StringWriter, get the bytes from the String, and use them with ByteArrayResource.

Upvotes: 1

Related Questions