• Willkommen im Linux Club - dem deutschsprachigen Supportforum für GNU/Linux. Registriere dich kostenlos, um alle Inhalte zu sehen und Fragen zu stellen.

mails via php auslesen

Hy Leute, würde gern ein php script schreiben das mir alle mails ausliest und verarbeitet. bin schon so weit und hab in der shell die datei gefunden wo das postfach ist (via confixx angelegt). Z.B. web0p1. Jetzt würde ich gern via php auf diese datei zugreifen. Bekomm aber access denied zurück (verzeichnis /var/mails/web0p1). erstell ich einen link via ln in home/web0/html/ usw kommt file not found. Wie krieg ich das hin ?
 
A

Anonymous

Gast
pico NEUERSCRIPTNAME
cd DEINPOSTFACH
grep * "DEINSUCHBEGRIFF"
schliessen + speichern. und schon haste deine gesuchten Dinge auf StdOut, wenn du es in ne andere Datei schreiben willst, einfach " > NEUER;ZWEITERDATEINAME" an grep dranhängen
 
Du möchtest Dich mit den Sicherheitsoptionen von php vertraut machen, Stichwort: basedir.

Alternativ kannst Du ja auch einfach mit entsprechenden PHP-routinen über den Mailserver auf die Mails zugreifen
 
Ich hab mal eine Mailinglistensoftware in PHP geschrieben. Hier einige Auszüge, sollte das Problem lösen.

Diese Datei liest alle Mails aus einem Postfach und speichert sie in eine DB. Du musst das ganze noch ein wenig anpassen, falls Du keine DB hast, bzw. falls doch eben die Userdaten.
Code:
<?php
    /**
     *  Contains the equal named function
     *
     *  @package    nblist
     */

    /** Retrieves the mail from the mailbox and writes them to the pre Inbox */
    function retriever() {
        global  $__DB, $__CONFIG;
        if (mysql_connect($__DB['server'], $__DB['user'], $__DB['password'])
            && mysql_select_db($__DB['db'])) {
            
            //Getting Connection to the Mailserver
            $conn = getCon();
            if ($conn) {

                //Getting list of mails
                fputs($conn, "LIST\n");

                $run        = 0;
                $mailIDs    = array();
                while(true) {
                    //Counting run
                    $run++;

                    //Getting line
                    $line = trim(fgets($conn, 2048));
                    
                    //Breaking if Server returns a . cause this shows the end of the list
                    if($line == '.') {                    
                        break;
                    }
                    
                    //Forget the first line, cause it contains no nesseary data
                    if($run > 2) {
                        $linedata = explode(' ', $line);
                        $mailIDs[] = $linedata[0];
                    }
                }

                //Retrieving every mail
                if (sizeof($mailIDs) > 0) {
                    for ($i = 0; $i < sizeof($mailIDs); $i++) {
                        fputs($conn, "RETR " . $mailIDs[$i] . "\n");

                        //Composing lines of a mail to one string
                        $mailarray  = array();
                        $error      = false;
                        while ($line = fgets($conn, 2048)) {

                            //Breaking if Mail is finished
                            if (trim($line) == '.') {
                                break;
                            }

                            //Breaking if an error accured
                            if(strtolower(trim(substr($result, 0, strlen("-ERR")))) == strtolower("-ERR")) {
                                $error = true;                    
                                break;
                            }                

                            $mailarray[] = $line;
                        }

                        //Writing Mail to database if no error accured
                        if ($error == false) {
                            array_shift($mailarray);
                            $mailstring = implode('', $mailarray);
                            $data = analysemail($mailstring);
                            if (substr_count(strtolower($data['header']), strtolower('X-NBLIST-DONOTRESEND: true')) == 0) {
                                $id = mysql_result(mysql_query('SELECT MAX(id) FROM pre_inbox'), 0, 0) + 1;
                                $insert = @mysql_query('INSERT INTO pre_inbox SET id = \'' . $id . '\', data = \'' . mysql_escape_string($mailstring) . '\', stat = \'r\'');
                                if (! $insert) {
                                    $filename = uniqid(time());
                                    $fp = fopen('./system/data/' . $filename);
                                    fputs($fp, $mailstring);
                                    fclose($fp);
                                    mail($__CONFIG['admin'], 
                                         '[' . $__CONFIG['systemname'] . '] Couldn\'t save mail.', 
                                         'I\'m sorry to inform you, that I couldn\'t save a mail into'
                                         .' the database. I stored it to the file: ' . $filename,
                                         'From: ' . $__CONFIG['system_from'] . "\n");

                                    
                                }
                            }
                        }

                        //Deleting Message on Mailserver
                        if ($error == false) {
                            fputs($conn, 'DELE ' . $mailIDs[$i] . "\n");

                            //Fetching result (nessecary to make deletion work);
                            $line = fgets($conn, 2048);
                        }
                    }
                }

                //Logging of the Mailserver
                fputs($conn, "QUIT");
                fclose($conn);

            } else {
                return false;
            }
            
            mysql_close();
        } else {
            return false;
        }
    }

?>


Das hier analysiert die Mail und liefert die einzelnen werte als assoziativer Array zurück.
Code:
<?php

    /**
     *  Contains functin analysemail and analysemimebody
     *
     *  @package    nblist
     */
     
    /** Analyses the bodyparts of a mime mail */
    function analysemimebody($body, $boundary) {
        
            $ret['anhang'] = array();
            $einzel = explode('--' . $boundary, $body);
            
            //  Removing first and last part
            array_shift($einzel);
            array_pop($einzel);
            
            
            for($i = 0; $i < sizeof($einzel); $i++) {

                //  Body of the attachement
                $text = trim(substr(  $einzel[$i], strpos($einzel[$i], "\n\n")   )   );
            
                //  Content Type
                if(@preg_match('|Content-Type:(.*);|Ui', $einzel[$i], $result)) {
                    $contenttype    = trim($result[1]);
                } else {
                    $contenttype    = '';
                }

                // Charset
                if(@preg_match('|charset=(.*);|Ui', $einzel[$i], $result)) {
                    $charset    = trim($result[1]);
                } else {
                    $charset    = '';
                }
                
                //  Content Disposition
                if(@preg_match('|Content-Disposition:(.*);|Ui', $einzel[$i], $result)) {
                    $contentdisposition = trim($result[1]);
                } else {
                    $contentdisposition = '';
                }
                
                //  Filename
                if(@preg_match('|Content-Disposition:.*;.*filename="(.*)"|Uis', $einzel[$i], $result)) {
                    $filename = trim($result[1]);
                } else {
                    $filename = '';
                }               
                
                //  Content-Transfer-Encoding
                if(@preg_match('|Content-Transfer-Encoding:(["]?)(.*)\\1|i', $einzel[$i], $result)) {
                    $transferencoding = trim($result[2]);
                } else {
                    $transferencoding = '';
                }                 
                
                //  Puting data to an array
                if(preg_match('#multipart#Uis', $contenttype)) {
                    
                    //  The Attachment is a mulitpart thing again
                    $pattern = '|boundary=(["]?)(.*)\\1|i';
                    preg_match($pattern, $einzel[$i], $matches);
                    $boundary_neu = $matches[2];
                    
                    //  analysing this one to
                    $daten = analysemimebody($einzel[$i], $boundary_neu);
                    
                    //  Putting the data together
                    for($n = 0; $n < sizeof($daten['anhang']); $n++) {
                        $ret['anhang'][] = array('text' => $daten['anhang'][$n]['text'],
                                                 'contenttype' => $daten['anhang'][$n]['contenttype'],
                                                 'transferencoding' => $daten['anhang'][$n]['transferencoding'],
                                                 'filename' => $daten['anhang'][$n]['filename'],
                                                 'contentdisposition' => $daten['anhang'][$n]['contentdisposition']
                                                );                    
                    }
                }
                else {
                    $ret['anhang'][] = array('text' => $text,
                                             'contenttype' => $contenttype,
                                             'charset' => $charset,
                                             'transferencoding' => $transferencoding,
                                             'filename' => $filename,
                                             'contentdisposition' => $contentdisposition                                             
                                            );
                }
            }                    
        
        return $ret;    
    }
     

    /** Analyses a mail */
    function analysemail($mail) {       
        
        //  Replacing windows Style \r to \n
        $mail = str_replace("\r\n", "\n", $mail);        

        //  Sperating header and body
        $header =  trim(substr($mail, 0, strpos($mail, "\n\n")));
        $body   = trim(substr($mail, strpos($mail, "\n\n") + 1, strlen($mail)));                          
        
        $values['header'] = $header;
        $values['body'] = $body;
        
        //  Date
        if(@preg_match('|\nDate: (.*)\n|Ui', $header, $result)) {
            $values['date'] = $result[1];
        }        
        
        //  Subject
        if(@preg_match('#\nSubject: (.*)\n(\n|[a-zA-Z0-9])#Uis', $header, $result)) {
            $values['subject'] = $result[1];
        }

        //  Content-Type of the mail
        if(@preg_match('#\nContent-Type: (.*)[;|\n]#Ui', $header, $result)) {
            $values['contenttype_header'] = $result[1];
        }

        //  Content-Transfer-Encoding
        if(@preg_match('|Content-Transfer-Encoding:(["]?)(.*)\\1|i', $header, $result)) {
            $values['transferencoding'] = trim($result[2]);
        } else {
            $values['transferencoding'] = '';
        }                 

        //  Content Disposition
        if(@preg_match('|Content-Disposition:(.*)|Ui', $header, $result)) {
            $values['contentdisposition'] = trim($result[1]);
        } else {
            $values['contentdisposition'] = '';
        }

        //Charset Header
        if(@preg_match('#charset.*=(.*)[;|\n]#Ui', $header, $result)) {
            $values['charset_header'] = $result[1];
        }

        //Format Header
        if(@preg_match('#format.*=(.*)[;|\n]#Ui', $header, $result)) {
            $values['charset_format'] = $result[1];
        }
        
        //  Reply-To:
        if(@preg_match('|\nReply-To: (.*)\n|Ui', $header, $result)) {           
            $values['replyto'] = $result[1];
        }
            
        //  From:
        if(@preg_match('|\nFrom: (.*)\n|Ui', $header, $result)) {          
    
            $values['from'] = $result[1];
            
            //  Splitting From in adress and name
            if(@preg_match('|<(.*)>|Ui', $values['from'], $result)) {                 
                $values['from_mail'] = $result[1];
                $values['from_name'] = trim(str_replace('<' . $values['from_mail'] . '>', '', $values['from']));
            } elseif (@preg_match('|\((.*)\)|Ui', $values['from'], $result1)) {
                $values['from_name'] = $result1[1];
                $values['from_mail'] = trim(str_replace('(' . $values['from_name'] . ')', '', $values['from']));
            } else {
                $values['from_mail'] = $values['from'];
                $values['from_name'] = $values['from'];
            }
            
            
        }

        // Protocoll 
        $pattern = '|protocol=(["]?)(.*)\\1|i';
        if(@preg_match($pattern, $header, $result2)) {
            $values['protocol'] = $result2[2];
        }

        // micalg
        $pattern = '|micalg=(["]?)(.*)\\1|i';
        if(@preg_match($pattern, $header, $result2)) {
            $values['micalg'] = $result2[2];
        }
            
        // To:
        if(@preg_match('#\nTo: (.*)\n(\n|[a-zA-Z0-9])#Uis', $header, $result)) {
            $values['to'] = $result[1];

            //Seperating values if there are more than one reciepient
            $tos = array();
            $tos = explode(',', $values['to']);
            for ($i = 0; $i < sizeof($tos); $i++) {
                //  Splitting to to name and mailadress
                if(@preg_match('|<(.*)>|Ui', $tos[$i], $result)) {                 
                    $values['to_mail'][$i] = $result[1];
                    $values['to_name'][$i] = trim(str_replace('<' . $values['to_mail'][$i] . '>', '', $tos[$i]));
                } elseif (@preg_match('|\((.*)\)|Ui', $tos[$i], $result1)) {
                    $values['to_name'][$i] = $result1[1];
                    $values['to_mail'][$i] = trim(str_replace('(' . $values['to_name'][$i] . ')', '', $tos[$i]));
                } else {
                    $values['to_mail'][$i] = trim($tos[$i]);
                    $values['to_name'][$i] = trim($tos[$i]);
                }            
            }
        }

        // CC:
        if(@preg_match('#\nCC: (.*)\n(\n|[a-zA-Z0-9])#Uis', $header, $result)) {
            $values['cc'] = $result[1];

            //Seperating values if there are more than one reciepient
            $ccs = array();
            $ccs = explode(',', $values['cc']);
            for ($i = 0; $i < sizeof($ccs); $i++) {
                //  Splitting cc cc name and mailadress
                if(@preg_match('|<(.*)>|Ui', $ccs[$i], $result)) {                 
                    $values['cc_mail'][$i] = $result[1];
                    $values['cc_name'][$i] = trim(str_replace('<' . $values['cc_mail'][$i] . '>', '', $ccs[$i]));
                } elseif (@preg_match('|\((.*)\)|Ui', $ccs[$i], $result1)) {
                    $values['cc_name'][$i] = $result1[1];
                    $values['cc_mail'][$i] = trim(str_replace('(' . $values['cc_name'][$i] . ')', '', $ccs[$i]));
                } else {
                    $values['cc_mail'][$i] = trim($ccs[$i]);
                    $values['cc_name'][$i] = trim($ccs[$i]);
                }            
            }
        }
            
            
        // Checking if its a mime mail
        if(@preg_match('|\nContent-Type: multipart|Ui', $header, $result)) {
            $values['mime_mail'] = 'yes';
            
            //  Reading Boundary 
            $pattern = '|boundary=(["]?)(.*)\\1|i';
            if(@preg_match($pattern, $header, $result2)) {
                $values['boundary'] = $result2[2];
            }
        }
        else {
            $values['mime_mail'] = 'no';
        }

        //  Reading body
        if($values['mime_mail'] == 'no') {
            $values['text'] = $body;
        }
        else {
            //  Analying all multipart parts
            $daten = analysemimebody($values['body'], $values['boundary']);
            $values = array_merge($values, $daten);
            
            //  Setting $values['text'] and $values['text_html']
            $values['text'] = '';
            $values['text_html'] = '';
            
            $text_gefunden = false;         //makes sure, that only the first text found is used.
            $text_html_gefunden = false;
            for($i = 0; $i < sizeof($values["anhang"]); $i++) {
                //Plain Text
                if(strtolower($values['anhang'][$i]['contenttype']) == strtolower('text/plain') && ! $text_gefunden) {
                    $values['text'] = $values['anhang'][$i]['text'];
                    $text_gefunden = true;
                }
                
                //HTML Text
                if(strtolower($values['anhang'][$i]['contenttype']) == strtolower('text/html') && ! $text_html_gefunden) {
                    $values['text_html'] = $values['anhang'][$i]['text'];
                    $text_html_gefunden = true;
                }                
            }                    
        }      
            
        //Returning
        return $values;
    }
?>


Alternativ kannst Du auch über die IMAP Funktionen auf (POP) Postfächer zugreifen, aber nicht jeder Provider hat IMAP mit drin.
 
nbkr schrieb:
Alternativ kannst Du auch über die IMAP Funktionen auf (POP) Postfächer zugreifen, aber nicht jeder Provider hat IMAP mit drin.

was denn jetzt ;) POP oder IMAP .... wenn Du einen IMAP-Server hast, brauchst Du keine POP (heute eher POP3) Postfächer mehr ;) SCNR.
 
Die IMAP Funktionen von PHP heißen IMAP Funktionen, können logischerweise auf IMAP Postfächer zugreifen aber auch auf POP3 Postfächer.
 
Oben