Java
Java
Fetch Single Email by UID or Sequence Number
Assuming the UID is known, download a single email by UID from an IMAP mail server.Chilkat Java 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;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
CkImap imap = new CkImap();
// Connect to an IMAP server.
// Use TLS
imap.put_Ssl(true);
imap.put_Port(993);
success = imap.Connect("imap.example.com");
if (success == false) {
System.out.println(imap.lastErrorText());
return;
}
// Login
success = imap.Login("***","***");
if (success == false) {
System.out.println(imap.lastErrorText());
return;
}
// Select an IMAP mailbox
success = imap.SelectMailbox("Inbox");
if (success == false) {
System.out.println(imap.lastErrorText());
return;
}
CkEmail email = new CkEmail();
int uid = 2014;
boolean isUid = true;
success = imap.FetchEmail(false,uid,isUid,email);
if (success == false) {
System.out.println(imap.lastErrorText());
return;
}
// Display the From and Subject
System.out.println(email.fromAddress());
System.out.println(email.subject());
// Display the Body property, which is the default body.
// If an email has an HTML body, the Body property contains
// the HTML source. Otherwise it contains the plain-text
// body.
System.out.println("---- EMAIL BODY ----");
System.out.println(email.body());
System.out.println("--------------------");
// Display the recipients:
int j;
for (j = 0; j <= email.get_NumTo() - 1; j++) {
System.out.println(email.getToName(j) + ", " + email.getToAddr(j));
}
for (j = 0; j <= email.get_NumCC() - 1; j++) {
System.out.println(email.getCcName(j) + ", " + email.getCcAddr(j));
}
// Show the total size of the email, including body and attachments:
System.out.println(email.get_Size());
// When a full email is downloaded, we would use the
// email.NumAttachments property in conjunction with the
// email.GetMailAttach* methods.
// However, when an email object contains only the header,
// we need to access the attachment info differently:
int numAttach = imap.GetMailNumAttach(email);
System.out.println(numAttach);
for (j = 0; j <= numAttach - 1; j++) {
System.out.println(imap.getMailAttachFilename(email,j));
int attachSize = imap.GetMailAttachSize(email,j);
System.out.println(" size = " + attachSize + " bytes");
}
System.out.println("--");
// Disconnect from the IMAP server.
success = imap.Disconnect();
}
}