Kategorien
PHP

PHP POP3 Mails aus Postfach auslesen

Um mit PHP an die E-Mails eines Postfaches zu gelangen über POP3, habe ich diese nützliche Testscript geschrieben. Damit lassen sich alle ungelesen E-Mails anzeigen mit Absender, Betreff, Datum und E-Mail-Body.

$mailserver="pop.foo.de";
$port="110/pop3";
$user="name@foode";
$pass="foo";
getEmailsImap($mailserver, $port, $user, $pass);

//open connection to mailbox, read all unread mails
function getEmailsImap($mailserver, $port, $user, $pass)
{
    $imap = imap_open( "{" . $mailserver . ":" . $port . "}INBOX", $user, $pass );
    if ($imap)
     {
        echo "Connected\n";
        $check = imap_mailboxmsginfo($imap);
        echo "Date: "     . $check->Date    . "<br />\n" ;
        echo "Driver: "   . $check->Driver  . "<br />\n" ;
        echo "Unread: "   . $check->Unread  . "<br />\n" ;
        echo "Size: "     . $check->Size    . "<br />\n" ;

        $totalrows = imap_num_msg($imap);
        //iterate through all unread mails
        for ($index = 0; $index < $totalrows; $index++)
        {
            $header = imap_header($imap, $index + 1);
             //get mail subject
            dump("<h1>".$header->subject."</h1>");
             //get mail sent date
            $prettydate = date(DateTime::ISO8601 , $header->udate);
            dump( $prettydate );
            //get email author
            $email = "{$header->from[0]->mailbox}@{$header->from[0]->host}";
            dump( $email );
            //get mail body
            dump( imap_body($imap, $index + 1));
        }
        //close connection to mailbox
        imap_close($imap);
        return true;
     }
     else
     {
         dump("Can't connect: " . imap_last_error());
         return false;
     }
}
function dump($var)
{
    echo "<pre><div align='left'>";
    print_r($var);
    echo "</div></pre>";
}