Sample code for 30+ languages & platforms
Java

Fetch a Single Message's MIME into a StringBuilder

See more IMAP Examples

Demonstrates the Chilkat Imap.FetchSingleAsMimeSb method, which downloads one message's MIME into a StringBuilder. The first argument is the message id, the second (bUid) selects UID vs sequence number, and the third is the StringBuilder, which is cleared first. This example downloads a message by UID and prints the MIME length.

Background: Chilkat interprets the received MIME as UTF-8. Messages using Base64 or quoted-printable transfer encoding are safe because their encoded bytes are ASCII. Raw 8bit or binary content, or unencoded text in a charset such as ISO-8859-1 or Shift_JIS, can be misinterpreted — in those cases use FetchSingleBd to get the exact bytes.

Chilkat Java Downloads

Java
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;

    //  Demonstrates the Imap.FetchSingleAsMimeSb method, which downloads one message's MIME into a
    //  StringBuilder.  The 1st argument is the message id, the 2nd (bUid) selects UID vs sequence
    //  number, and the 3rd is the StringBuilder (cleared first).

    CkImap imap = new CkImap();

    imap.put_Ssl(true);
    imap.put_Port(993);

    success = imap.Connect("imap.example.com");
    if (success == false) {
        System.out.println(imap.lastErrorText());
        return;
        }

    success = imap.Login("user@example.com","myPassword");
    if (success == false) {
        System.out.println(imap.lastErrorText());
        return;
        }

    success = imap.SelectMailbox("Inbox");
    if (success == false) {
        System.out.println(imap.lastErrorText());
        return;
        }

    //  Search for the message ids to download, returning UIDs.
    boolean wantUids = true;
    CkMessageSet msgSet = new CkMessageSet();
    success = imap.QueryMbx("ALL",wantUids,msgSet);
    if (success == false) {
        System.out.println(imap.lastErrorText());
        return;
        }

    if (msgSet.get_Count() > 0) {
        int uid = msgSet.GetId(0);

        //  Download the message's MIME into a StringBuilder.  The id is a UID.
        boolean useUid = true;
        CkStringBuilder sbMime = new CkStringBuilder();
        success = imap.FetchSingleAsMimeSb(uid,useUid,sbMime);
        if (success == false) {
            System.out.println(imap.lastErrorText());
            return;
            }

        System.out.println("MIME length: " + sbMime.get_Length() + " chars");
        }

    success = imap.Disconnect();
    if (success == false) {
        System.out.println(imap.lastErrorText());
        return;
        }
  }
}