Java Requires Chilkat v11.0.0+
Chilkat2 Java
Fetch Oldest/Newest IMAP Email
Emails may be downloaded by sequence number. Assuming the selected mailbox is not empty, the oldest email is at sequence number 1, and the newest email is at sequence number N. The FetchSingle method may be used to download by sequence number.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.Imap;
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("mail.testemail.net");
// Login
imap.login("***", "***");
// Select an IMAP mailbox
imap.selectMailbox("Inbox");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// After selecting a mailbox, the NumMessages property
// contains the number of emails in the selected mailbox.
int n = imap.getNumMessages();
if (n > 0) {
// The oldest email is always at sequence number 1.
boolean isUid = false;
Email oldestEmail = new Email();
try {
imap.fetchEmail(false, 1, isUid, oldestEmail);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Display the From and Subject
System.out.println(oldestEmail.getFromAddress());
System.out.println(oldestEmail.getSubject());
System.out.println("--");
// The newest email is at sequence number N:
Email newestEmail = new Email();
try {
imap.fetchEmail(false, n, isUid, newestEmail);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Display the From and Subject
System.out.println(newestEmail.getFromAddress());
System.out.println(newestEmail.getSubject());
}
// Disconnect from the IMAP server.
imap.disconnect();
}
}