Sample code for 30+ languages & platforms
CkJava Requires Chilkat v11.0.0+

Find and save an attachment and list inline images

See more Email Object Examples

Find an attachment by filename and media type, then save its decoded bytes to a path you choose. Enumerate inline resources separately to read their Content-IDs.

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkEmail email = new CkEmail();
    success = email.LoadEml("with-attachments.eml");
    if (success != true) {
        System.out.println(email.lastErrorText());
        return;
        }

    CkStringBuilder filename = new CkStringBuilder();
    CkStringBuilder mediaType = new CkStringBuilder();
    boolean found = false;
    int i = 0;
    while ((i < email.get_NumAttachments())) {
        filename.SetString(email.getAttachmentFilename(i));
        mediaType.SetString(email.getAttachmentContentType(i));
        if ((filename.ContentsEqual("agenda.csv",false) == true) && (mediaType.ContentsEqual("text/csv",false) == true) && (found == false)) {
            CkBinData data = new CkBinData();
            success = email.GetAttachmentBd(i,data);
            if (success != true) {
                System.out.println(email.lastErrorText());
                return;
                }

            success = data.WriteFile("received-agenda.csv");
            if (success != true) {
                System.out.println("Failed: data.WriteFile.");
                return;
                }

            System.out.println("Saved attachment: " + data.get_NumBytes() + " bytes.");
            found = true;
            }

        i = i+1;
        }

    if (found != true) {
        System.out.println("No matching attachment.");
        }

    i = 0;
    while ((i < email.get_NumRelatedItems())) {
        System.out.println("Related: " + email.getRelatedContentType(i) + "  Content-ID: " + email.getRelatedContentID(i));
        i = i+1;
        }
  }
}