我想发送带csv附件的电子邮件,而不必将csv文件存储在服务器上。
我创建了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();
}
我的电子邮件程序:
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, CharEncoding.UTF_8);
InternetAddress ad = new InternetAddress("test@gmail.com");
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;
}
所以我想将CsvPrinter转换为ByteArrayresource。
有办法吗?
答案 0 :(得分:1)
从StringWriter中获取字符串,从String中获取字节,并将其与ByteArrayResource一起使用。