Sample code for 30+ languages & platforms
Java

Zip an Email's Attachments into One File

See more Email Object Examples

Demonstrates the Chilkat Email.ZipAttachments method, which replaces all of an email's attachments with a single Zip file attachment having the specified filename. The original attachments are removed and packed into the Zip. This example adds two attachments and zips them into one.

Background: Bundling multiple attachments into a single .zip keeps a message tidy, compresses the payload, and works around recipients or gateways that limit the number of attachments. Note that the filename here (files.zip) names the attachment inside the message — it is not a path on disk. The reverse operation is UnzipAttachments.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;

public class ChilkatExample {

    public static void main(String[] args) {
        // Demonstrates the ZipAttachments method, which replaces all of an email's attachments
        // with a single Zip file attachment having the specified filename.  The original
        // attachments are removed and packed into the Zip.

        Email email = new Email();
        email.setSubject("Zip the attachments");

        email.addStringAttachment("a.txt", "first attachment");
        email.addStringAttachment("b.txt", "second attachment");
        System.out.println("NumAttachments before = " + email.getNumAttachments());

        // Replace all attachments with a single Zip attachment named "files.zip".
        try {
            email.zipAttachments("files.zip");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("NumAttachments after = " + email.getNumAttachments());
    }
}