Fetching mail from a POP3 server using php
Asked Answered
T

5

41

I am trying to fetch a mail from POP3 (I am using POP3 mail server and I am trying to fetch the mail content and store into a database table for my project.), but I can't find any PHP script for that, all are only for IMAP.

Do you know how to fetch mail from a POP3 server?

Thanks.

Titanic answered 2/7, 2010 at 10:46 Comment(0)
E
38

Somewhat surprisingly, PHP's imap library can be also used for working with POP3 mailboxes. Most of the advanced IMAP features won't work, of course (e.g. folders or fetching message parts), but the basic POP3 functionality is implemented.

The main difference is the option string that you're passing to imap_open - to quote that page:

// To connect to a POP3 server on port 110 on the local server, use:
$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

Other than that, it's fair sailing - you won't need more than imap_open, imap_num_msg, imap_body, imap_delete and imap_close for basic POP3 access.

Ecclesiasticus answered 2/7, 2010 at 10:52 Comment(0)
O
11

PHP's IMAP functions can deal with both IMAP and POP3 boxes.

These functions enable you to operate with the IMAP protocol, as well as the NNTP, POP3 and local mailbox access methods.

Be warned, however, that some IMAP functions will not work correctly with the POP protocol.

there is a User Contributed Note that provides an interesting snippet. You may want to take a look at it. I can't say anything about its quality but from the surface, it looks okay.


Below, the Contributed Note:

For all the people coming here praying for:

1) a dead-easy way to read MIME attachments, or

2) a dead-easy way to access POP3 folders

Look no further.

function pop3_login($host,$port,$user,$pass,$folder="INBOX",$ssl=false)
{
    $ssl=($ssl==false)?"/novalidate-cert":"";
    return (imap_open("{"."$host:$port/pop3$ssl"."}$folder",$user,$pass));
}
function pop3_stat($connection)        
{
    $check = imap_mailboxmsginfo($connection);
    return ((array)$check);
}
function pop3_list($connection,$message="")
{
    if ($message)
    {
        $range=$message;
    } else {
        $MC = imap_check($connection);
        $range = "1:".$MC->Nmsgs;
    }
    $response = imap_fetch_overview($connection,$range);
    foreach ($response as $msg) $result[$msg->msgno]=(array)$msg;

    return $result;
}
function pop3_retr($connection,$message)
{
    return(imap_fetchheader($connection,$message,FT_PREFETCHTEXT));
}
function pop3_dele($connection,$message)
{
    return(imap_delete($connection,$message));
}
function mail_parse_headers($headers)
{
    $headers=preg_replace('/\r\n\s+/m', '',$headers);
    preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)?\r\n/m', $headers, $matches);
    foreach ($matches[1] as $key =>$value) $result[$value]=$matches[2][$key];
    return($result);
}
function mail_mime_to_array($imap,$mid,$parse_headers=false)
{
    $mail = imap_fetchstructure($imap,$mid);
    $mail = mail_get_parts($imap,$mid,$mail,0);
    if ($parse_headers) $mail[0]["parsed"]=mail_parse_headers($mail[0]["data"]);
    return($mail);
}
function mail_get_parts($imap,$mid,$part,$prefix)
{    
    $attachments=array();
    $attachments[$prefix]=mail_decode_part($imap,$mid,$part,$prefix);
    if (isset($part->parts)) // multipart
    {
        $prefix = ($prefix == "0")?"":"$prefix.";
        foreach ($part->parts as $number=>$subpart) 
            $attachments=array_merge($attachments, mail_get_parts($imap,$mid,$subpart,$prefix.($number+1)));
    }
    return $attachments;
}
function mail_decode_part($connection,$message_number,$part,$prefix)
{
    $attachment = array();

    if($part->ifdparameters) {
        foreach($part->dparameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'filename') {
                $attachment['is_attachment'] = true;
                $attachment['filename'] = $object->value;
            }
        }
    }

    if($part->ifparameters) {
        foreach($part->parameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'name') {
                $attachment['is_attachment'] = true;
                $attachment['name'] = $object->value;
            }
        }
    }

    $attachment['data'] = imap_fetchbody($connection, $message_number, $prefix);
    if($part->encoding == 3) { // 3 = BASE64
        $attachment['data'] = base64_decode($attachment['data']);
    }
    elseif($part->encoding == 4) { // 4 = QUOTED-PRINTABLE
        $attachment['data'] = quoted_printable_decode($attachment['data']);
    }
    return($attachment);
}
Orji answered 2/7, 2010 at 10:52 Comment(1)
Few bugs in this code sample (replace $imap by $connection in pop3_stat) ; return $response in pop3_list.....Chloropicrin
G
3

you can use pop3 e-mail client class which can Access to e-mail mailboxes using the POP3 protocol. You will get each e-mail body part and can store it in database, even you can retrieve attached files without deleting the original mail in the inbox. For more go to http://www.phpclasses.org/package/2-PHP-Access-to-e-mail-mailboxes-using-the-POP3-protocol.html

Germ answered 28/5, 2011 at 10:11 Comment(0)
P
1

IF you have PHP build with IMAP support, it would be easy, see IMAP documentation (especially comments at this page) at http://php.net/manual/en/book.imap.php

UPDATE: to clarify my answer - as you see in the comments and function reference, PHP imap_* functions can be used also for pop3.

Paladin answered 2/7, 2010 at 10:51 Comment(0)
C
0

You can open a socket connection and send POP3 commands directly to your server to retrieve emails.

The code below opens a connection to the server, authenticates, requests a count of available messages, downloads them one by one, then deletes them from the server. During the interaction with the server, if an unexpected response is received, the connection is closed.

You should be able to alter the code below to get what you need.

Create a config.ini file and populate it like this:

pop3_host=your.pop3.host
pop3_user=youremailusername
pop3_pass=youremailpassword

Obviously substitute the values with your actual host, username and password. Then change the parse_ini_file parameter to point to your config.ini file.

<?php

$config = parse_ini_file('/path/to/config.ini');
$stream = fsockopen('ssl://' . $config['pop3_host'], 995, $error_code, $error_message);
if (!$stream) {
    die('fsockopen ' . $error_code . ' ' . $error_message);
}
$s = fgets($stream);
if (substr($s, 0, 3) !== '+OK') {
    quit('OPEN');
}
chat('USER ' . $config['pop3_user']);
chat('PASS ' . $config['pop3_pass']);
$s = chat('STAT');
$stat = explode(' ', $s);
if (count($stat) !== 3) {
    quit('STAT+');
}
$n = (integer)$stat[1];
for ($i = 1; $i <= $n; $i++) {
    chat('RETR ' . $i);
    $file = fopen($i . '.msg', 'wb');
    if (!$file) {
        quit('FILE ' . $i);
    }
    while (true) {
        $s = fgets($stream);
        if ($s === '.' . "\r\n") {
            fclose($file);
            break;
        }
        fputs($file, $s);
    }
    chat('DELE ' . $i);
}
chat('QUIT');
fclose($stream);

function chat(string $command): string {
    global $stream;
    fputs($stream, $command . "\r\n");
    $s = fgets($stream);
    if (substr($s, 0, 3) !== '+OK') {
        quit(explode(' ', $command)[0]);
    }
    return $s;
}

function quit(string $message): void {
    global $stream;
    fputs($stream, 'QUIT' . "\r\n");
    $s = fgets($stream);
    fclose($stream);
    die($message);
}
Celinacelinda answered 17/6, 2022 at 1:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.