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

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 PHP Downloads

PHP
<?php

use Chilkat2\Email;
use Chilkat2\Imap;

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

$imap = new Imap();

// Connect to an IMAP server.
// Use TLS
$imap->Ssl = true;
$imap->Port = 993;
try {
    $imap->Connect('imap.example.com');

    // Login
    $imap->Login('***', '***');

    // Select an IMAP mailbox
    $imap->SelectMailbox('Inbox');

    $email = new Email();

    $uid = 2014;
    $isUid = true;

    $imap->FetchEmail(false, $uid, $isUid, $email);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Display the From and Subject
echo $email->FromAddress, "\n";
echo $email->Subject, "\n";

// 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.
echo "---- EMAIL BODY ----\n";
echo $email->Body, "\n";
echo "--------------------\n";

// Display the recipients:
for ($j = 0; $j < $email->NumTo; $j++) {
    echo $email->GetToName($j), ', ', $email->GetToAddr($j), "\n";
}

for ($j = 0; $j < $email->NumCC; $j++) {
    echo $email->GetCcName($j), ', ', $email->GetCcAddr($j), "\n";
}

// Show the total size of the email, including body and attachments:
echo $email->Size, "\n";

// 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:
$numAttach = $imap->GetMailNumAttach($email);
echo $numAttach, "\n";

for ($j = 0; $j < $numAttach; $j++) {
    echo $imap->GetMailAttachFilename($email, $j), "\n";
    $attachSize = $imap->GetMailAttachSize($email, $j);
    echo '    size = ', $attachSize, " bytes\n";
}

echo "--\n";

// Disconnect from the IMAP server.
$imap->Disconnect();