I am using AWS SES. I am trying to attach a ZIP file to an email of a CSV that is made in memory. I am close but am having a hard time figuring this out.
Currently, when I receive the email i am still getting a .CSV but upon opening it appears that the content is compresses. How do I zip the file and not the content?
The file is currently being received as a bye array:
public void emailReport(
byte[] fileAttachment,
String attachmentType,
String attachmentName,
List<String> emails) throws MessagingException, IOException {
......
// Attachment
messageBodyPart = new MimeBodyPart();
byte[] test = zipBytes(attachmentName, fileAttachment);
// DataSource source = new ByteArrayDataSource(fileAttachment, attachmentType);
DataSource source = new ByteArrayDataSource(test, "application/zip");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
multipart.addBodyPart(messageBodyPart);
log.info("Successfully attached file.");
message.setContent(multipart);
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
client.sendRawEmail(rawEmailRequest);
System.out.println("Email sent!");
log.info("Email successfully sent.");
} catch (Exception ex) {
log.error("Error when sending email");
ex.printStackTrace();
}
}
Here is a method that zips a file:
public static byte[] zipBytes(String filename, byte[] input) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry(filename);
entry.setSize(input.length);
zos.putNextEntry(entry);
zos.write(input);
zos.closeEntry();
zos.close();
return baos.toByteArray();
}
Thanks for the help, if you have any additional questions please let me know and I will provide whatever code, etc. is needed.
The filename should have the .zip extension.
messageBodyPart.setFileName("file.zip");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With