Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to attach a ZIP file to an email in Java?

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.

like image 582
reedb89 Avatar asked Jul 21 '17 13:07

reedb89


1 Answers

The filename should have the .zip extension.

messageBodyPart.setFileName("file.zip");
like image 94
J.Profi Avatar answered Oct 17 '22 01:10

J.Profi