Fetching mail from a POP3 server using php

Fetching mail from a POP3 server using php

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

Stefan Bogdanescu

Founder & Senior Architect

Fetching Mail from a POP3 Server Using PHP

While IMAP is the industry standard for mail protocols because it allows clients to access messages directly on the server, POP3 remains relevant in specific architectures where you need to download, decrypt, or parse email content to store it locally. If your project requires ingesting emails from a POP3 server and persisting them in a database, you cannot rely on IMAP libraries; you must interact with the POP3 protocol directly using PHP's pop3 extension.

The core mechanism involves establishing a connection to the server, authenticating, retrieving the list of messages, fetching each message's headers and body, and finally disconnecting. Unlike IMAP, which often leaves copies on the server, POP3 is designed to download messages so they can be archived locally or deleted from the remote server.

Establishing the Connection

To begin, you must ensure the pop3 extension is enabled in your PHP configuration. You can verify this by checking if the function pop3_close() exists. The connection process starts with pop3_popen(), which opens a socket to the mail server. This function returns a resource handle that you will use for all subsequent operations.

$host = 'pop.example.com';
$user = 'your_username';
$pass = 'your_password';
$port = 110; // Standard POP3 port, or 995 for POP3S (SSL)

// Open connection
$stream = pop3_popen($host, $port);

if ($stream === false) {
    die('Connection failed: ' . error_get_last()['message']);
}

Authentication and SSL Considerations

Once the stream is open, you must send authentication credentials. The standard sequence involves sending a user command followed by the pass command. However, a critical technical detail arises here: many modern hosts require Secure Sockets Layer (SSL) to encrypt the transmission of passwords. Standard POP3 transmits data in plaintext, which is a security risk.

If your server supports POP3 over SSL (usually port 995), you must wrap the stream using fsockopen with SSL options before applying POP3 functions, or use the stream_socket_enable_crypto() function to encrypt an existing connection. Failing to handle SSL correctly when required will result in authentication failures or exposed credentials.

// Example of enabling SSL on an established stream (if supported)
if (!stream_socket_enable_crypto($stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
    die('SSL negotiation failed');
}

After encryption is established (or if using plain text on port 110), you proceed with standard POP3 commands via pop3_cmd(). You send the USER command, wait for a response, and then send the PASS command. Always check the return value of these functions; a negative return code indicates an error in the protocol exchange.

Retrieving and Parsing Messages

The workflow changes significantly once you decide how to handle the downloaded data. A common misconception is that POP3 provides a direct method to fetch raw headers or bodies easily like IMAP does. It does not. The typical approach involves fetching the message number by number. You must first use pop3_get_msgs() to retrieve the list of available messages on the server.

To actually get the content, you iterate through the message numbers and use pop3_retr() (retrieve). This function returns the raw header and body for a specific message. Since POP3 often requires deleting messages after retrieval to free up space, you must call pop3_dele() before disconnecting if your goal is archival.

$messages = pop3_get_msgs($stream);

foreach ($messages as $msgNum) {
    // Retrieve the message content (headers + body)
    $content = pop3_retr($stream, $msgNum);
    
    if ($content === false) {
        continue; // Handle error or skip message
    }

    // Parse raw content into headers and body
    list($headers, $body) = explode("\r\n\r\n", $content, 2);
    
    // Store in database here...
}

Post-Retrieval Cleanup

A defining characteristic of POP3 is that it assumes the client will take ownership of the data. If you do not delete the messages from the server using pop3_dele(), your mailbox will fill up quickly, potentially blocking new emails. After processing a batch, you must call pop3_stat() if you need to verify counts, and eventually pop3_quit() followed by pop3_close() to terminate the session gracefully.

// Mark messages for deletion
foreach ($messages as $msgNum) {
    pop3_dele($stream, $msgNum);
}

// Commit changes and quit
pop3_rset($stream); // Reset/delete flags
pop3_quit($stream);
pop3_close($stream);

Why Not Use IMAP Instead?

The decision to use POP3 over IMAP usually stems from specific constraints. If you need the raw MIME structure of an email for parsing, or if your application logic requires deleting emails immediately after download to manage local storage limits, POP3 is the tool. However, the lack of built-in header manipulation in the PHP extension makes manual parsing essential. You must manually split the raw string returned by pop3_retr() to extract MIME types, subjects, and attachment metadata.

For complex mail processing needs, consider integrating with a dedicated mail fetching service or using a library that abstracts these low-level POP3 commands. If you are building a full-stack application on Laravel, ensure your database schema is optimized for storing raw MIME bodies if you intend to parse them later, as this increases storage requirements significantly compared to storing only headers.

Our network