java附加zip到电子邮件

时间:2017-07-21 13:41:38

标签: java javamail

我正在使用AWS SES,并尝试将zip文件附加到内存中制作的CSV的电子邮件中。我很接近,但我很难搞清楚这一点。目前,当我收到电子邮件时,我仍然收到.CSV,但在打开时,似乎内容是压缩的。如何压缩文件而不是内容?该文件当前是作为一个再见阵列接收的。

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 bytes功能

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();
}

感谢您的帮助,如果您有任何其他问题,请告诉我,我将提供任何代码等。需要。

1 个答案:

答案 0 :(得分:3)

文件名应该是.zip扩展名。

messageBodyPart.setFileName("file.zip");