11

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.

informatik01
  • 16,038
  • 10
  • 74
  • 104
reedb89
  • 382
  • 3
  • 15
  • What's the value of `fileAttachment` at this line: `byte[] test = zipBytes(attachmentName, fileAttachment);`? – baudsp Jul 21 '17 at 13:50
  • It is a String.getBytes(); – reedb89 Jul 21 '17 at 13:55
  • 1
    My bad, I intended to ask about `attachmentName`. Because I think the name of the attachement in the email will have this value. And if it's `file.csv` and not `file.zip`, that's why you would have a csv instead of a zip in your email. Edit: See J. Profi's Answer – baudsp Jul 21 '17 at 13:59

1 Answers1

4

The filename should have the .zip extension.

messageBodyPart.setFileName("file.zip");
J.Profi
  • 76
  • 4