Java attach zip for email

I am using AWS SES and trying to attach a zip file to a CSV email that is made in memory. I'm close, but it's hard for me to understand this. Currently, when I receive an email, I still receive .CSV, but when opened it seems that the contents are compressed. How to make a zip file, not content? The file is currently accepted 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();

    }

}

zip byte function

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 additional questions, please let me know and I will provide any code, etc. necessary.

+4
source share
1 answer

The file name must have a .zip extension.

messageBodyPart.setFileName("file.zip");
+3
source

Source: https://habr.com/ru/post/1681967/


All Articles