2010-07-27 5 views
0

본 사이트의 이메일 메시지 파서를 작성하려고합니다. 내가 결국 할 일은 메시지가 특정 전자 메일 주소에서 오는 경우 첨부 파일이있는 메시지를 반복하고 첨부 파일을 저장하는 것입니다.PHP imap 함수를 사용하는 데 문제가 있습니다.

이것은 초기 테스트 일 뿐이지 만 문제가 발생했습니다. 아래 주석을 참조하십시오.

<?php 
    echo "Loading..."."<br />\n"; 
    $mailuser="[email protected]"; 

    echo "User=$mailuser"."<br />\n";; 
    $mailpass="mypassword"; 
    echo "Pass=$mailpass"."<br />\n"; 
    // had to use this because we have SSL on site and regular port 110 didn't work 
    $mailhost="{localhost:995/pop3/ssl/novalidate-cert}"; 
    echo "Host=$mailhost"."<br />\n"; 

    $mailbox=imap_open($mailhost,$mailuser,$mailpass) or die("<br />\nFAILLED! ".imap_last_error()); 
    $check = imap_check($mailbox); 
    // last message parsed will be stored in the file msgcounter.dat 
    $firstmsg = file_get_contents('msgcounter.dat') + 1; 
    $lastmsg = $firstmsg+$check->Recent; // should be == last msg index + count of latest messages 
    echo 'First:'.$firstmsg.' - Last:'.$lastmsg."<br>"; 
    $result = imap_fetch_overview($mailbox,"$firstmsg:$lastmsg"); 
    print_r($result); 
    foreach ($result as $overview) { 
    echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from} 
    {$overview->subject}\n"; 
    } 
    // the following approach didn't work either, Kept getting warnings about 
    // Bad message number 
    // 
    // Some messages in the sequence HAVE been deleted. 
    /* 
    for ($index = $firstmsg-1; $index <= ($lastmsg); $index++) { 
    if (strlen(trim(imap_fetchheader($mailbox, $index))) > 0) { 
     echo 'in message index loop:'.$index; 
    } 
    } 
    */ 
    imap_close($mailbox); 
echo "completed.". "<br />\n";; 
?> 
+2

무엇을 묻고 있습니까? – funwhilelost

+0

내 전체 게시물을 읽지 않았습니까? 그렇다면 어떤 부분을 이해하지 못했습니까? – MB34

+0

게시물을 두 번 읽은 후에 명시된 문제를 찾을 수 없습니다. 코드에 문제가있는 것 같지만 코드를 실행할 때까지는 알 수 없습니다. 주석 처리 된 부분입니까? 다른 곳인가요? – deceze

답변

0

문제는 내가이 라인에서 IMAP 사서함을 확인되지 않았 음을했다 :

$mailhost="{localhost:995/pop3/ssl/novalidate-cert}";

이 올바른 라인을 사용하는 것입니다

$mailhost="{localhost/imap/ssl/novalidate-cert}";

0

IMAP는 표준이 좋지 않고 구현이 나쁜 곳입니다. 약간의 욕설 (또는 어)이 마음에 들지 않는다면 악명 높은 IMAP rant by a Ruby library dev에 흥미로운 통찰력이 있습니다.

더러운 작업을 수행하려면 using someone else's code을 고려해야합니다.

+0

나는 내가 인터넷에서 발견 한 다른 코드에 내 코드를 기초로하고있다. ;-) – MB34

+0

Ooooo, eeeek, Zend 함수가 아니다 !!! – MB34

+0

그 루비 호언 장담은 재미있었습니다. 이제 SMTP 작업 그룹이 엉덩이를 벗어나 릴레이를 검증 할 수 있다면 스팸 메일이 종료됩니다! – MB34

0

좋아, 나는 지금 일하기 위해 노력하고있는 것의 큰 부분을 가지고있다. 내가 남긴 유일한 문제는 실제로 메시지를 다른 "폴더"로 이동시키는 것입니다. imap_mail_move는 POP3 메일 박스에서는 지원되지 않습니다. 다른 방법을 찾아야합니다.

마지막으로 내가 가지고있는 문제는 내가 방금 연 메시지와 함께 어떤 메시지 파일이 있는지 알고있는 것입니다. 파일을 옮기기 위해 std rename() 함수를 사용할 수 있지만 courierimapuiddb 파일에서 msgnum을 조회 할 수 있다는 것을 알았습니다. 파일 이름이 거기에 있습니다. 여기

파일의 이동을 제외하고, 지금 작업 한 코드입니다 :

<?php 

function showProgressMsg($msg) 
{ 
    echo $msg."<br>"; 
    ob_flush(); 
flush(); 
    usleep(2500); 
} 
    $mailpass="mymailpass"; 
    $mailhost="{localhost:995/pop3/ssl/novalidate-cert}"; 
    $mailuser="[email protected]"; 
    include "libs/database/db_mysql.php"; 
    $db = new Database; 

    $debug=false; 
    if($_GET['debug']= 'yes') { 
    $debug = true; 
    ini_set('output_buffering', 'Off'); 
    ob_start(); 
    } 

    if($debug) {showProgressMsg('Opening Mailbox');} 

    $mailbox=imap_open($mailhost,$mailuser,$mailpass) or die("<br />\nFAILLED! ".imap_last_error()); 

    // The IMAP.xml file contains the email address and user_id of the users that we accept 
    // their files via email 
    if($debug) {showProgressMsg('Reading IMAP.xml');} 
    $xml = simplexml_load_string(file_get_contents('IMAP.xml')); 
    $result = $xml->xpath('item'); 
    while(list(, $node) = each($result)) { 
    $email = $node->LI_email; 
    $user_id = $node->LI_user_id; 
    $search = "RECENT FROM \"$email\""; 

    if($debug) {showProgressMsg('Searching for '.$email);} 
    $result2 = imap_search($mailbox, $search); 
    if($result2) { 
     $index = $result2[0]; 
     $structure = imap_fetchstructure($mailbox, $index); 

     $attachments = array(); 
     if(isset($structure->parts) && count($structure->parts)) { 
     if($debug) {showProgressMsg('Handling attachments');} 
     for($i = 0; $i < count($structure->parts); $i++) { 
      $attachments[$i] = array(
      'is_attachment' => false, 
      'filename' => '', 
      'name' => '', 
      'attachment' => ''); 

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

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

      if($attachments[$i]['is_attachment']) { 
      $attachments[$i]['attachment'] = imap_fetchbody($mailbox, $index, $i+1, FT_PEEK); 
      if($structure->parts[$i]->encoding == 3) { // 3 = BASE64 
       $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']); 
      } 
      elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE 
       $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']); 
      } 
      }    
     } // for($i = 0; $i < count($structure->parts); $i++) 
     } // if(isset($structure->parts) && count($structure->parts)) 

     // Now add a record into the file_upload table 
     for($i = 0; $i < count($attachments); $i++) { 
     if (strlen(trim($attachments[$i]['filename'])) > 0) { 
      $path_parts = pathinfo($attachments[$i]['filename']); 
      if($debug) {showProgressMsg('Processing '.$attachments[$i]['filename']);} 
      if(strtolower($path_parts['extension']) == 'zip') { 
      // I am going to do something different with ziped files    
      $filename = 'file_uploads/temp/'.$user_id.'_'.$path_parts['filename'].'_'.date('m_d_Y').'.'.$path_parts['extension']; 
      $fp = fopen($filename, "w"); 
      fwrite($fp, $attachments[$i]['attachment']); 
      fclose($fp);      
      $zip = new ZipArchive(); 
      if ($zip->open($filename) !== TRUE) { 
       die ('Could not open archive'); 
      } 
      $zippedfile = $zip->statIndex(0); 
      $path_parts = pathinfo($zippedfile['name']); 
      $newfilename = 'file_uploads/'.$user_id.'_'.$path_parts['filename'].'_'.date('m_d_Y').'.'.$path_parts['extension']; 
      $zip->extractTo('file_uploads/', $zippedfile['name']); 
      $zip->close();   
      unlink($filename); 
      rename('file_uploads/'.$zippedfile['name'], $newfilename); 
      $filestr = preg_replace('`[\r\n]+`',"\n", file_get_contents($newfilename)); 
      $fp = fopen($newfilename, "w+"); 
      fwrite($fp, $filestr); 
      fclose($fp);      
      // remove the directory from the filename 
      $filename = $user_id.'_'.$path_parts['filename'].'_'.date('m_d_Y').'.'.$path_parts['extension']; 
      // Now insert into file_upload table 
      $insert_sql = "INSERT INTO `file_upload` VALUES(NULL,$user_id, '$filename', 0, NOW())"; 
      $db->query($insert_sql) or die("Can't insert record"); 
      } else { 
      $filename = 'file_uploads/'.$user_id.'_'.$path_parts['filename'].'_'.date('m_d_Y').'.'.$path_parts['extension']; 
      $fp = fopen($filename, "w"); 
      $attachments[$i]['attachment'] = preg_replace('`[\r\n]+`',"\n",$attachments[$i]['attachment']); 
      fwrite($fp, $attachments[$i]['attachment']); 
      fclose($fp); 
      // remove the directory from the filename 
      $filename = $user_id.'_'.$path_parts['filename'].'_'.date('m_d_Y').'.'.$path_parts['extension']; 
      // Now insert into file_upload table 
      $insert_sql = "INSERT INTO `file_upload` VALUES(NULL,$user_id, '$filename', 0, NOW())"; 
      $db->query($insert_sql) or die("Can't insert record:".mysql_error()); 
      } 
     } // if (strlen(trim($attachments['name'])) > 0 
     } // for($i = 0; $i < count($attachments); $i++) 
     // Now move the message to completed uploads mailbox 
     // imap_mail_move copies the message and then sets the deleted flag. 
     // Found out that imap_mail_move is unsupported on POP3 accounts 
     // imap_mail_move($mailbox, "$index", "INBOX/completed+uploads") or die("can't move: ".imap_last_error()); 

     // This is a stop gap to circumvent the message being processed twice 
     // Found out that this also is not supported by POP3 boxes 
     if($debug) {showProgressMsg('Setting \Seen flag');} 
     imap_setflag_full($mailbox, "$index", "\Seen \Flagged"); 

     // This clears out the deleted messages 
     // imap_expunge($mailbox); 

     /* 
     So, I'm going to have to open the courierimapuiddb file and locate the msgnum 
     then get the filename and use rename() to move the file to the completed uploads 
     directory. 
     */ 
    if($debug) {showProgressMsg(',oving message');} 

    } // if($result2) 
    // Now, move the message to completed uploads 
    } // while(list(, $node) = each($result)) 
    if($debug) { 
    showProgressMsg('Closing mailbox and cleaning up'); 
    ob_flush(); 
    flush(); 
    ob_end_clean(); 
    ini_set('output_buffering', 4096); 
    } 
    imap_close($mailbox); 
?> 
관련 문제