Java Requires Chilkat v11.0.0+
Java
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 Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.Imap;
import com.chilkatsoft.chilkat2.MessageSet;
public class ChilkatExample {
public static void main(String[] args) {
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Imap imap = new Imap();
imap.setSsl(true);
imap.setPort(993);
imap.setRequireSslCertVerify(true);
imap.setPeekMode(true);
imap.setAutoDownloadAttachments(true);
try {
imap.connect("imap.example.com");
imap.login("MAIL_USER", "MAIL_PASSWORD");
imap.selectMailbox("INBOX");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
MessageSet matches = new MessageSet();
try {
imap.queryMbx("SUBJECT \"Sample message\"", true, matches);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
if (matches.getCount() == 0) {
System.out.println("No matching message in INBOX.");
try {
imap.disconnect();
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
return;
}
// The search returned UIDs. Use the same identifier type for the fetch.
long uid = matches.getId(0);
Email email = new Email();
try {
imap.fetchEmail(false, uid, true, email);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Mailbox INBOX, UIDVALIDITY " + imap.getUidValidity() + ", UID " + uid);
try {
imap.disconnect();
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// The downloaded Email remains usable after disconnecting.
System.out.println("Subject: " + email.getSubject() + " Files: " + email.getNumAttachments());
try {
email.saveEml("imap-received.eml");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Saved imap-received.eml.");
}
}