2012-07-01 52 views
12

Làm cách nào để tải tệp đính kèm từ email này?imap - nhận tệp đính kèm

Email này được gửi từ một máy tính táo và Cơ cấu email không giống như bất kỳ khác (ngạc nhiên) .. ở đây phần với sự sắp xếp là một trong những khía cạnh sâu hơn nữa ..

Các kịch bản làm việc với mỗi khác email, nơi một phần với các tập tin là trong chiều đầu tiên, nhưng không phải với điều này một

$part->dparameters[0]->value trả về tên tập tin, nhưng strlen($data) lợi nhuận 0

imap dòng

$structure = imap_fetchstructure($this->stream, $this->msgno); 

if(isset($structure->parts)){ 
    print_r($structure->parts); 
    $this->parse_parts($structure->parts); 
} 

function parse_parts($parts){ 
    foreach($parts as $section => $part){ 
     if(isset($part->parts)){ 

      // some mails have one extra dimension 
      $this->parse_parts($part->parts); 

     } 
     elseif(isset($part->disposition)){ 
      if(in_array(strtolower($part->disposition), array('attachment','inline'))){ 
       $data = imap_fetchbody($this->stream, $this->msgno, $section+1); 
       echo $part->dparameters[0]->value.' '.strlen($data)."\n"; 
      } 
     } 
    } 
} 

print_r

Array 
(
    [0] => stdClass Object 
     (
      [type] => 0 
      [encoding] => 0 
      [ifsubtype] => 1 
      [subtype] => PLAIN 
      [ifdescription] => 0 
      [ifid] => 0 
      [lines] => 15 
      [bytes] => 173 
      [ifdisposition] => 0 
      [ifdparameters] => 0 
      [ifparameters] => 1 
      [parameters] => Array 
       (
        [0] => stdClass Object 
         (
          [attribute] => CHARSET 
          [value] => us-ascii 
         ) 

       ) 

     ) 

    [1] => stdClass Object 
     (
      [type] => 1 
      [encoding] => 0 
      [ifsubtype] => 1 
      [subtype] => MIXED 
      [ifdescription] => 0 
      [ifid] => 0 
      [bytes] => 23420 
      [ifdisposition] => 0 
      [ifdparameters] => 0 
      [ifparameters] => 1 
      [parameters] => Array 
       (
        [0] => stdClass Object 
         (
          [attribute] => BOUNDARY 
          [value] => Apple-Mail=_800896E0-A9C9-456E-B063-79CED9DD4FD7 
         ) 

       ) 

      [parts] => Array 
       (
        [0] => stdClass Object 
         (
          [type] => 0 
          [encoding] => 0 
          [ifsubtype] => 1 
          [subtype] => HTML 
          [ifdescription] => 0 
          [ifid] => 0 
          [bytes] => 136 
          [ifdisposition] => 0 
          [ifdparameters] => 0 
          [ifparameters] => 1 
          [parameters] => Array 
           (
            [0] => stdClass Object 
             (
              [attribute] => CHARSET 
              [value] => us-ascii 
             ) 

           ) 

         ) 

        [1] => stdClass Object 
         (
          [type] => 3 
          [encoding] => 3 
          [ifsubtype] => 1 
          [subtype] => PDF 
          [ifdescription] => 0 
          [ifid] => 0 
          [bytes] => 17780 
          [ifdisposition] => 1 
          [disposition] => INLINE 
          [ifdparameters] => 1 
          [dparameters] => Array 
           (
            [0] => stdClass Object 
             (
              [attribute] => FILENAME 
              [value] => 057 - LPJ - Stik og labels.pdf 
             ) 

           ) 

          [ifparameters] => 1 
          [parameters] => Array 
           (
            [0] => stdClass Object 
             (
              [attribute] => NAME 
              [value] => 057 - LPJ - Stik og labels.pdf 
             ) 

           ) 

         ) 

        [2] => stdClass Object 
         (
          [type] => 0 
          [encoding] => 4 
          [ifsubtype] => 1 
          [subtype] => HTML 
          [ifdescription] => 0 
          [ifid] => 0 
          [lines] => 75 
          [bytes] => 4931 
          [ifdisposition] => 0 
          [ifdparameters] => 0 
          [ifparameters] => 1 
          [parameters] => Array 
           (
            [0] => stdClass Object 
             (
              [attribute] => CHARSET 
              [value] => us-ascii 
             ) 

           ) 

         ) 

       ) 

     ) 

) 
+0

Tôi không hiểu làm thế nào một email được gửi * TỪ * a Mac có thể là bất kỳ khác với bất kì thứ khác. Bạn đã so sánh tiêu đề email với một email được gửi từ một loại tài khoản khác để tìm hiểu chính xác cách chúng khác nhau? Trừ khi "từ" bạn có nghĩa là nó được lưu trữ trên một máy chủ email trên máy Mac. – Mike

+0

Cấu trúc cơ thể khác với bất kỳ phần nào khác .. phần có tệp là một chiều sâu hơn trong cấu trúc hơn là khác – clarkk

+0

Tôi đã nói tiêu đề thư. Xem mã nguồn của email và so sánh chúng để xem có gì khác biệt. So sánh cách mỗi người trong số họ gửi tệp đính kèm và điều đó có thể cung cấp cho bạn ý tưởng về những gì đang diễn ra. – Mike

Trả lời

12

Bạn không cung cấp đúng số phần cho các tệp đính kèm lồng nhau. Bạn cần chuyển số phần trong bước đệ quy.

function parse_parts($parts, $parentsection = ""){ 
    foreach($parts as $subsection => $part){ 
     $section = $parentsection . ($subsection + 1); 
     if(isset($part->parts)){ 

      // some mails have one extra dimension 
      $this->parse_parts($part->parts, $section . "."); 

     } 
     elseif(isset($part->disposition)){ 
      if(in_array(strtolower($part->disposition), array('attachment','inline'))){ 
       $data = imap_fetchbody($this->stream, $this->msgno, $section); 
       echo 'Getting section ' . $section; 
       echo $part->dparameters[0]->value.' '.strlen($data)."\n"; 
      } 
     } 
    } 
} 

(chưa được kiểm tra, nhưng nên làm điều đúng ...)

+0

Hi .. Nó vẫn không hoạt động: -/ – clarkk

+0

xấu của tôi .. nó hoạt động! hehe cảm ơn – clarkk

1

Tôi không biết cụ thể về email Mac, nhưng đây là một số mã tôi có đi qua từng phần để xem nếu nó là một "đính kèm" và lưu tập tin ở đâu đó vì vậy tôi có thể gọi nó sau.

$body = imap_fetchstructure($box, $i); 
$attachments = ''; 
$att = count($body->parts); 
if($att >=2) { 
for($a=0;$a<$att;$a++) { 
if($body->parts[$a]->disposition == 'ATTACHMENT') { 
$file = imap_base64(imap_fetchbody($box, $i, $a+1)); 
$string = genRandomString(); 
    if(!file_exists('/var/www/email_store/'.$_SESSION['site_user_id'])) { 
     mkdir('/var/www/email_store/'.$_SESSION['site_user_id'].'/'); 
    } 
    $attachments .= $body->parts[$a]->dparameters[0]->value.'[#]'.$string.','; 
    file_put_contents('/var/www/email_store/'.$_SESSION['site_user_id'].'/'.$string,$file); 
    } 
}  
+0

Điều này giả định rằng thư được lưu trữ cục bộ. Điều gì xảy ra nếu nó được lưu trữ trên một máy chủ IMAP từ xa? – Mike

+0

Đó là sự thật, nhưng việc tập tin đính kèm vẫn hoạt động, bạn chỉ có thể bỏ qua lưu nó cục bộ và đặt nó ở một nơi khác. – romo

+0

@Mike: Nó không giả định rằng thư được lưu trữ cục bộ - nó liên lạc với máy chủ IMAP, nhận thư đính kèm và sau đó lưu thư cục bộ. – Stobor

5

Các mã tiếp theo cho bạn thấy các thư mục và email trong INBOX

$mailbox = imap_open ("{correo.servidor.com:993/imap/ssl/novalidate-cert}INBOX", "[email protected]", "PASSWORD"); 

    if (!$mailbox){ 
     die('murio'); 
    } 

    echo "<h1>Buzones</h1>\n"; 
    $carpetas = imap_listmailbox($mailbox, "{correo.patronato.unam.mx:993}", "*"); 

    if ($carpetas == false) { 
     echo "Llamada fallida<br />\n"; 
    } else { 
     foreach ($carpetas as $val) { 
      echo $val . "<br />\n"; 
     } 
    } 

    echo "<h1>Cabeceras en INBOX</h1>\n"; 
    $cabeceras = imap_headers($mailbox); 

    if ($cabeceras == false) { 
     echo "Llamada fallida<br />\n"; 
    } else { 
     foreach ($cabeceras as $val) { 
      echo $val . "<br />\n"; 
     } 
    } 



    $numMessages = imap_num_msg($mailbox); 
    for ($i = $numMessages; $i > 0; $i--) { 
     $header = imap_header($mailbox, $i); 

     $fromInfo = $header->from[0]; 
     $replyInfo = $header->reply_to[0]; 

     // print_r($header); 

     $details = array(
      "fromAddr" => (isset($fromInfo->mailbox) && isset($fromInfo->host)) 
       ? $fromInfo->mailbox . "@" . $fromInfo->host : "", 
      "fromName" => (isset($fromInfo->personal)) 
       ? $fromInfo->personal : "", 
      "replyAddr" => (isset($replyInfo->mailbox) && isset($replyInfo->host)) 
       ? $replyInfo->mailbox . "@" . $replyInfo->host : "", 
      "replyName" => (isset($replyTo->personal)) 
       ? $replyto->personal : "", 
      "subject" => (isset($header->subject)) 
       ? $header->subject : "", 
      "udate" => (isset($header->udate)) 
       ? $header->udate : "", 
      "Unseen" => (isset($header->Unseen)) 
       ? $header->Unseen : "-" 
     ); 
     $uid = imap_uid($mailbox, $i); 

     echo "<ul>"; 
     echo "<li><strong>From:</strong>" . $details["fromName"]; 
     echo " " . $details["fromAddr"] . "</li>"; 
     echo "<li><strong>Subject:</strong> " . $details["subject"] . "</li>"; 
     echo "<li><strong>Estatus:</strong> " . $details["Unseen"] . "</li>"; 
     echo '<li><a href="test_imap_attachment.php?folder=' . $folder . '&uid=' . $i . '">Read</a></li>'; 
     echo "</ul>"; 
    } 


    imap_close($mailbox); 

Mã test_imap_attachment.php rằng hiển thị cho bạn Tệp đính kèm

function getAttachments($imap, $mailNum, $part, $partNum) { 
    $attachments = array(); 

    if (isset($part->parts)) { 
     foreach ($part->parts as $key => $subpart) { 
      if($partNum != "") { 
       $newPartNum = $partNum . "." . ($key + 1); 
      } 
      else { 
       $newPartNum = ($key+1); 
      } 
      $result = getAttachments($imap, $mailNum, $subpart, 
       $newPartNum); 
      if (count($result) != 0) { 
       array_push($attachments, $result); 
      } 
     } 
    } 
    else if (isset($part->disposition)) { 
     // print_r($part); 
     if (strtoupper($part->disposition) == "ATTACHMENT") { 
      $partStruct = imap_bodystruct($imap, $mailNum, $partNum); 
      $attachmentDetails = array(
       "name" => $part->dparameters[0]->value, 
       "subtype" => $partStruct->subtype, 
       "partNum" => $partNum, 
       "enc"  => $partStruct->encoding 
      ); 
      return $attachmentDetails; 
     } 
    } 

    return $attachments; 
} 

$mailbox = imap_open ("{correo.servidor.com:993/imap/ssl/novalidate-cert}INBOX", "[email protected]", "PASSWORD"); 

$uid = $_GET['uid']; 

$mailStruct = imap_fetchstructure($mailbox, $uid); 

$attachments = getAttachments($mailbox, $uid, $mailStruct, ""); 

echo "Attachments: "; 
echo "<ul>"; 
foreach ($attachments as $attachment) { 
    echo '<li><a href="test_imap_download.php?func=' . $func . '&folder=' . $folder . '&uid=' . $uid . 
     '&part=' . $attachment["partNum"] . '&enc=' . $attachment["enc"] . '">' . 
     $attachment["name"] . "</a></li>"; 
} 
echo "</ul>"; 

Mã tiếp theo lưu tệp trên cùng một máy chủ: t est_imap_download.php đang

function downloadAttachment($imap, $uid) { 
    $structure = imap_fetchstructure($imap, $uid); 
    $attachments = ''; 
    if(isset($structure->parts) && count($structure->parts)) { 
     for($i=0; $i<count($structure->parts); $i++) { 
      if(strtoupper($structure->parts[$i]->disposition) == 'ATTACHMENT') { 

       $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($imap, $uid, $i+1); 
        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']); 
        } 
       } 

       file_put_contents('directorio/'.$attachments[$i]['filename'], $attachments[$i]['attachment']); 

      } 
     } 
    } 
} 

$mailbox = imap_open ("{correo.servidor.com:993/imap/ssl/novalidate-cert}INBOX", "[email protected]", "PASSWORD"); 


$uid  = $_GET["uid"]; 
$partNum = $_GET["partNum"]; 

downloadAttachment($mailbox, $uid); 

Tôi đã sử dụng từ các trang này:

http://www.sitepoint.com/exploring-phps-imap-library-2/

Downloading attachments to directory with IMAP in PHP, randomly works

Các vấn đề liên quan