2016-04-19 183 views
-1

我試圖創建一段代碼,它將進入郵箱並取出特定文件的附件。到目前爲止,我只能查看是否有附件或電子郵件上是否有附件。Php電子郵件附件提取

但我希望它能夠將附件從電子郵件中取出並保存到指定的目錄中。我試圖拿出的附件的類型是.jpg

我試過了一堆我在谷歌上找到的不同代碼,我一直在試圖調整它以適應我的代碼,但到目前爲止,我一直沒有找到任何可以正常工作的東西。

我想知道是否有人能夠幫助我創建一段代碼,能夠將附件從電子郵件中取出並存儲到目錄中。

謝謝。

<?php 

    /* connect to email */ 
    $hostname = '{*****.com:110/pop3}INBOX'; 
    $username = '*****'; 
    $password = '*****'; 

    // try to connect 
    $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error()); 

    // grab emails 
    $emails = imap_search($inbox,'ALL'); 

    // Search for the 39th email, which has an attachment 
    $count = 39; 


    // Fetch all the information about an email 
    $attachment = imap_fetchstructure($inbox, $count); 


    // find out how may parts the object has 
    $numparts = count($attachment->parts); 

// find if if multipart message 
if ($numparts >= 2) { 


    foreach ($attachment->parts as $part) { 

     if ($part->disposition == "INLINE") { 
     // inline message. Show number of lines 

     printf("Inline message has %s lines<BR>", $part->lines); 

     } elseif ($part->disposition == "ATTACHMENT") { 
     // an attachment 

     echo "Attachment found!"; 
     // print out the file name 
     echo "Filename: ", $part->dparameters[0]->value; 

     } 

    } 

} 
    //} 
    else { 
    // only one part so get some useful info 
    echo "No attachment"; 
} 

imap_close($imap); 
?> 

回答

0

代替imap_search我以前imap_check來獲取消息的概述,下面的工作。 走了過來與imap_check找到的消息,這是你如何解壓附件的二進制數據:

$mbox = imap_open(. . . .); 
    $IMAPobj = imap_check($inbox); 

    $start = $IMAPobj->Nmsgs-30; 
    $end = $IMAPobj->Nmsgs; 
    $result = imap_fetch_overview($inbox,"$start:$end",0); 

    $count = $end; 
    foreach ($result as $overview) { 
     $parts = mail_mime_to_array($inbox, $count); 
     foreach($parts as $part) { 
      if(@$part['filename'] || @$part['name']) { 

       $partName = $part['filename'] ? $part['filename'] : $part['name']; 
       echo "Attachment name is " . basename($partName); 
       echo "\n"; 

       if(preg_match(. . . write here a regex to detect ".jpg" in $partName . . .)) { 
        echo "Found file! Extracting binary data..."; 

        $fileContents = $part['data']; 
        file_put_contents("attachment.jpg", $fileContents); 
       } 
      } 
     } 
    } 
+0

謝謝,我會試試這個。 –