Sample code for 30+ languages & platforms
Java

Save All Email Attachments to a Directory

See more Email Object Examples

Demonstrates the Chilkat Email.SaveAllAttachments method, which saves all of the email's attachments to a directory. If the directory or any of its components do not exist, Chilkat creates them automatically. This example adds two attachments and saves them.

Background: Each attachment is written using its own filename. Because those filenames come from the sender and may collide, consider the OverwriteExisting property (which can auto-generate unique names) and RemoveAttachmentPaths (which strips embedded path info) to keep saved files safe and non-clobbering — important when processing untrusted incoming mail.

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 SaveAllAttachments method, which saves all attachments to a directory.
        // If the directory (or any of its components) does not exist, Chilkat creates it.

        Email email = new Email();
        email.setSubject("Save all attachments");

        email.addStringAttachment("a.txt", "first attachment");
        email.addStringAttachment("b.txt", "second attachment");

        // Save every attachment into the specified directory.
        try {
            email.saveAllAttachments("qa_output/attachments");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Saved all attachments.");

        // Note: The path "qa_output/..." is a relative local filesystem path,
        // relative to the current working directory of the running application.
    }
}