JavaScript Requires Chilkat v11.0.0+
JavaScript
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.
Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat
v11.4.0 or greater.
var success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
var imap = new CkImap();
imap.Ssl = true;
imap.Port = 993;
imap.RequireSslCertVerify = true;
imap.PeekMode = true;
imap.AutoDownloadAttachments = true;
success = imap.Connect("imap.example.com");
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
success = imap.Login("MAIL_USER","MAIL_PASSWORD");
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
success = imap.SelectMailbox("INBOX");
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
var matches = new CkMessageSet();
success = imap.QueryMbx("SUBJECT \"Sample message\"",true,matches);
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
if (matches.Count == 0) {
console.log("No matching message in INBOX.");
success = imap.Disconnect();
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
return;
}
// The search returned UIDs. Use the same identifier type for the fetch.
var uid = matches.GetId(0);
var email = new CkEmail();
success = imap.FetchEmail(false,uid,true,email);
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
console.log("Mailbox INBOX, UIDVALIDITY " + imap.UidValidity + ", UID " + uid);
success = imap.Disconnect();
if (success !== true) {
console.log(imap.LastErrorText);
return;
}
// The downloaded Email remains usable after disconnecting.
console.log("Subject: " + email.Subject + " Files: " + email.NumAttachments);
success = email.SaveEml("imap-received.eml");
if (success !== true) {
console.log(email.LastErrorText);
return;
}
console.log("Saved imap-received.eml.");