Java Requires Chilkat v11.0.0+
Chilkat2 Java
Fetch 1st N Headers of Search Results
Calls Search to get a message set, then downloads the 1st N messages in the message set. There are two equivalent ways of doing it: (1) iterate from 0 to N-1 and download each message individually, or (2) create a new message set that contains the 1st N messages and pass it to FetchHeaders. Both are demonstrated here.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) {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Imap imap = new Imap();
// Connect to an IMAP server.
// Use TLS
imap.setSsl(true);
imap.setPort(993);
try {
imap.connect("imap.example.com");
// Login
imap.login("****", "****");
// Select an IMAP mailbox
imap.selectMailbox("Inbox");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Get the message IDs of all the emails in the mailbox
// We can choose to fetch UIDs or sequence numbers.
boolean fetchUids = true;
MessageSet messageSet = new MessageSet();
try {
imap.queryMbx("ALL", fetchUids, messageSet);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
int numFound = messageSet.getCount();
if (numFound == 0) {
System.out.println("No messages found.");
return;
}
// Get the 1st 10 messages in messageSet.
int upperBound = 10;
if (numFound < upperBound) {
upperBound = numFound;
}
int i = 0;
boolean bUid = messageSet.getHasUids();
boolean headerOnly = true;
Email email = new Email();
while (i < upperBound) {
try {
imap.fetchEmail(headerOnly, messageSet.getId(i), bUid, email);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println(i + ": " + email.getSubject());
i = i + 1;
}
// Disconnect from the IMAP server.
imap.disconnect();
}
}