How to use IMAP in PHP to fetch mail body content?

How to use IMAP in PHP to fetch mail body content?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Hidden Format of IMAP: Fetching Email Bodies Correctly

The core issue preventing your script from displaying email content lies in how imap_fetchbody() handles multipart messages. When you connect to a server like Gmail and see text immediately, it often works because the specific message structure is simple (plain text only). However, most modern mail servers, including yours ({myserver/pop3/novalidate-cert}), store emails as multipart structures by default.

This means an email isn't just one big block of text; it's a container holding multiple parts, such as a text/plain version and a text/html version. Your current code calls imap_fetchbody($inbox, $email_number, 2). In the IMAP standard, the number passed to this function refers to the specific part ID within the message hierarchy.

For a simple single-part email, part ID 1 is the body and 2 might be non-existent or empty. For a multipart email, the structure typically looks like:

  • Part 1: The MIME headers (often empty or ignored).
  • Part 2: Often an attachment or a specific encoded chunk.
  • Part 3: The actual text/plain body.

By hardcoding 2, you are likely fetching an attachment or a fragment rather than the main message content, which results in empty output. To fix this, you must inspect the message structure first. You need to use imap_fetchstructure() to map out the parts of the email before attempting to fetch the body.

Here is the corrected approach using imap_fetchbody() with dynamic part retrieval:

/* Fetch the structure to understand the message hierarchy */
$structure = imap_fetchstructure($inbox, $email_number);

/* Check if there are parts (attachments or multiple formats) */
if ($structure && isset($structure->parts)) {
    /* Iterate through parts to find the one that is NOT an attachment */
    foreach ($structure->parts as $i => $part) {
        /* Skip attachments (where filename exists) and multipart containers */
        if (isset($part->dparameters[0]) && $part->dparameters[0]->attribute == 1) {
            continue;
        }
        
        /* Fetch the body of the current part */
        // Use '2' for multipart messages because part 1 is usually headers/empty
        // For single part, '1' is sufficient.
        $message = imap_fetchbody($inbox, $email_number, ($i + 1));
        
        /* Decode encoded words if present (e.g., "=?UTF-8?B?...?=") */
        $message = imap_mime_header_decode($message);
        
        /* Reconstruct the decoded string */
        $decoded = '';
        foreach ($message as $part) {
            $decoded .= $part->text . ($part->language ? "[$part->language]" : '');
        }
    }
} else {
    /* Handle single-part messages where structure->parts does not exist or is empty */
    // For single part, we usually fetch part 1, but often '2' is needed if the first part is headers
    // However, a safer generic approach for single part is:
    $message = imap_fetchbody($inbox, $email_number, '1'); 
}

Handling Encoded Text and Decoding

Even after fetching the correct part ID, you will often see garbled text like =?UTF-8?B?...?= or =?ISO-8859-1?Q?...?. This is MIME encoded text. The raw string returned by imap_fetchbody() is not human-readable yet. You must use imap_mime_header_decode() to convert these into readable strings, as shown in the example above.

Alternative: Using IMAP FETCH with Multiple Flags

If you need both plain text and HTML versions simultaneously (common for rich email clients), relying on imap_fetchbody() requires checking which part corresponds to text/plain and which to text/html. A more robust method involves fetching specific parts based on their MIME type found in the structure.

Alternatively, you can use the FETCH command with multiple flags to get the body directly if your PHP IMAP extension supports it efficiently, though the loop through parts is generally safer for cross-server compatibility.

Why This Fails on Your Server but Works on Gmail

Gmail's web interface normalizes content before delivery in some contexts, or their specific server configuration might return a single-part MIME structure even when HTML is present, effectively hiding the complexity from simple scripts. Your local mail server likely adheres strictly to RFC 2046 standards, exposing the full multipart tree. Ignoring the structure and hardcoding part numbers (2) is a recipe for failure on standard IMAP servers.

If you are building this within a Laravel application, consider utilizing packages that abstract these low-level details, such as php-imap wrappers or dedicated mail libraries, but understanding the underlying imap_fetchstructure logic remains essential for debugging connectivity issues across different providers.

Our network