CkJava Requires Chilkat v11.0.0+
CkJava
Find an email by subject and fetch it by IMAP UID
See more Email Object Examples
Search the selected INBOX by subject and fetch the first matching UID into an Email. The example requests complete attachment bodies and uses peek mode to preserve the read flag. Configure your own IMAP TLS endpoint and credentials.
Chilkat CkJava Downloads
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.
CkImap imap = new CkImap();
imap.put_Ssl(true);
imap.put_Port(993);
imap.put_RequireSslCertVerify(true);
imap.put_PeekMode(true);
imap.put_AutoDownloadAttachments(true);
success = imap.Connect("imap.example.com");
if (success != true) {
System.out.println(imap.lastErrorText());
return;
}
success = imap.Login("MAIL_USER","MAIL_PASSWORD");
if (success != true) {
System.out.println(imap.lastErrorText());
return;
}
success = imap.SelectMailbox("INBOX");
if (success != true) {
System.out.println(imap.lastErrorText());
return;
}
CkMessageSet matches = new CkMessageSet();
success = imap.QueryMbx("SUBJECT \"Sample message\"",true,matches);
if (success != true) {
System.out.println(imap.lastErrorText());
return;
}
if (matches.get_Count() == 0) {
System.out.println("No matching message in INBOX.");
success = imap.Disconnect();
if (success != true) {
System.out.println(imap.lastErrorText());
return;
}
return;
}
// The search returned UIDs. Use the same identifier type for the fetch.
int uid = matches.GetId(0);
CkEmail email = new CkEmail();
success = imap.FetchEmail(false,uid,true,email);
if (success != true) {
System.out.println(imap.lastErrorText());
return;
}
System.out.println("Mailbox INBOX, UIDVALIDITY " + imap.get_UidValidity() + ", UID " + uid);
success = imap.Disconnect();
if (success != true) {
System.out.println(imap.lastErrorText());
return;
}
// The downloaded Email remains usable after disconnecting.
System.out.println("Subject: " + email.subject() + " Files: " + email.get_NumAttachments());
success = email.SaveEml("imap-received.eml");
if (success != true) {
System.out.println(email.lastErrorText());
return;
}
System.out.println("Saved imap-received.eml.");
}
}