简体   繁体   English

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

[英]How to attach a ZIP file to an email in Java?

I am using AWS SES.我正在使用 AWS SES。 I am trying to attach a ZIP file to an email of a CSV that is made in memory.我正在尝试将 ZIP 文件附加到在内存中制作的 CSV 电子邮件。 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.目前,当我收到电子邮件时,我仍然收到 .CSV 文件,但在打开时,内容似乎已被压缩。 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.感谢您的帮助,如果您有任何其他问题,请告诉我,我将提供所需的任何代码等。

文件名应具有 .zip 扩展名。

messageBodyPart.setFileName("file.zip");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM