如何在Java中将ZIP文件附加到电子邮件?

11

我正在使用AWS SES。我试图将一个在内存中创建的CSV的ZIP文件附加到电子邮件中。我已经接近成功,但是仍然很难弄清楚。

目前,当我收到邮件时,我仍然会得到一个.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();

    }

}

这里有一种压缩文件的方法:

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

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


在这一行代码中,fileAttachment的值是多少:byte[] test = zipBytes(attachmentName, fileAttachment); - baudsp
它是一个String.getBytes(); - reedb89
1
我的错,我本意是想问关于“attachmentName”的。因为我认为电子邮件中的附件名称将具有此值。如果它是“file.csv”而不是“file.zip”,那么您会在电子邮件中收到csv而不是zip。编辑:请参见J. Profi的答案。 - baudsp
1个回答

4
文件名应该具有 .zip 扩展名。
messageBodyPart.setFileName("file.zip");

我的注意细节的习惯真是让我抓狂!这个方法解决了问题 :) 感谢你的帮助! - reedb89

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接