Sample code for 30+ languages & platforms
CkPhp 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 CkPhp Downloads

CkPhp
<?php

include("chilkat.php");

$success = false;

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

$imap = new CkImap();
$imap->put_Ssl(true);
$imap->put_Port(993);
$imap->put_RequireSslCertVerify(true);
$imap->put_PeekMode(true);
$imap->put_AutoDownloadAttachments(true);
$success = $imap->Connect('imap.example.com');
if ($success != true) {
    print $imap->lastErrorText() . "\n";
    exit;
}

$success = $imap->Login('MAIL_USER','MAIL_PASSWORD');
if ($success != true) {
    print $imap->lastErrorText() . "\n";
    exit;
}

$success = $imap->SelectMailbox('INBOX');
if ($success != true) {
    print $imap->lastErrorText() . "\n";
    exit;
}

$matches = new CkMessageSet();
$success = $imap->QueryMbx('SUBJECT \'Sample message\'',true,$matches);
if ($success != true) {
    print $imap->lastErrorText() . "\n";
    exit;
}

if ($matches->get_Count() == 0) {
    print 'No matching message in INBOX.' . "\n";
    $success = $imap->Disconnect();
    if ($success != true) {
        print $imap->lastErrorText() . "\n";
        exit;
    }

    exit;
}

//  The search returned UIDs. Use the same identifier type for the fetch.
$uid = $matches->GetId(0);
$email = new CkEmail();
$success = $imap->FetchEmail(false,$uid,true,$email);
if ($success != true) {
    print $imap->lastErrorText() . "\n";
    exit;
}

print 'Mailbox INBOX, UIDVALIDITY ' . $imap->get_UidValidity() . ', UID ' . $uid . "\n";
$success = $imap->Disconnect();
if ($success != true) {
    print $imap->lastErrorText() . "\n";
    exit;
}

//  The downloaded Email remains usable after disconnecting.
print 'Subject: ' . $email->subject() . '  Files: ' . $email->get_NumAttachments() . "\n";

$success = $email->SaveEml('imap-received.eml');
if ($success != true) {
    print $email->lastErrorText() . "\n";
    exit;
}

print 'Saved imap-received.eml.' . "\n";

?>