Sample code for 30+ languages & platforms
Node.js Requires Chilkat v11.0.0+

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 Node.js Downloads

Node.js
NODEJS_PRELUDE

function chilkatExample() {

    var success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    var imap = new chilkat.Imap();
    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 chilkat.MessageSet();
    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 chilkat.Email();
    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.");

}

chilkatExample();