使用PHP中的IMAP下载附件到目录,随机工作

28
我在这里找到了一份用PHP从IMAP下载附件到目录的代码。 http://www.nerdydork.com/download-pop3imap-email-attachments-with-php.html
我稍微修改了一下。
        $structure = imap_fetchstructure($mbox, $jk);
        $parts = ($structure->parts);

        $structure = imap_fetchstructure($mbox, $jk);
        $parts = ($structure);
为了使其正常运行,否则我会收到一个关于stdClass未定义名为$parts的属性的错误。这样做,我就能够下载所有附件。不过,最近我又测试了一下,它没用了。好吧,它失败了6次,第7次成功了,然后从此再也没有成功过。我想这可能与我搞砸了部件处理有关,因为每个消息的count($parts)都返回1,所以我认为它没有找到任何附件。

由于它曾经一次性下载所有附件而没有问题,我有信心说东西被搞乱的区域就在这里。在这段代码块之前是一个for循环,遍历邮箱中的每个消息,在它之后是一个循环,只是为每个imap结构遍历$parts。感谢您提供的任何帮助。我查看了php.net上的imap_fetchstructure页面,但无法弄清楚自己错在哪里。

编辑:在撰写问题并打字之后,我刚刚仔细检查了文件夹,所有内容都出现了。我觉得我快发疯了。自几分钟前我开始打字之后,我还没有运行过代码,对我来说它需要这么长时间才能触发没有道理。我邮箱中有大约800封邮件,但我认为,既然它在PHP的最后打印了我的语句,那么所有文件创建工作都已完成。


你需要选择一个答案,Nick。 - MB34
5个回答

55

这是完美的可行答案,请尝试。

此示例能够正常运行并下载所有附件,没有任何问题。

<?php

set_time_limit(3000); 

/* connect to gmail with your credentials */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'YOUR_USERNAME'; 
$password = 'YOUR_PASSWORD';

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

$emails = imap_search($inbox, 'FROM "abc@gmail.com"');

/* if any emails found, iterate through each email */
if($emails) {

    $count = 1;

    /* put the newest emails on top */
    rsort($emails);

    /* for every email... */
    foreach($emails as $email_number) 
    {

        /* get information specific to this email */
        $overview = imap_fetch_overview($inbox,$email_number,0);

        $message = imap_fetchbody($inbox,$email_number,2);

        /* get mail structure */
        $structure = imap_fetchstructure($inbox, $email_number);

        $attachments = array();

        /* if any attachments found... */
        if(isset($structure->parts) && count($structure->parts)) 
        {
            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($inbox, $email_number, $i+1);

                    /* 3 = BASE64 encoding */
                    if($structure->parts[$i]->encoding == 3) 
                    { 
                        $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                    }
                    /* 4 = QUOTED-PRINTABLE encoding */
                    elseif($structure->parts[$i]->encoding == 4) 
                    { 
                        $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                    }
                }
            }
        }

        /* iterate through each attachment and save it */
        foreach($attachments as $attachment)
        {
            if($attachment['is_attachment'] == 1)
            {
                $filename = $attachment['name'];
                if(empty($filename)) $filename = $attachment['filename'];

                if(empty($filename)) $filename = time() . ".dat";
                $folder = "attachment";
                if(!is_dir($folder))
                {
                     mkdir($folder);
                }
                $fp = fopen("./". $folder ."/". $email_number . "-" . $filename, "w+");
                fwrite($fp, $attachment['attachment']);
                fclose($fp);
            }
        }
    }
} 

/* close the connection */
imap_close($inbox);

echo "all attachment Downloaded";

?>

更多信息请查看链接

http://www.codediesel.com/php/downloading-gmail-attachments-in-php-an-update/


1
这对我来说完美地解决了问题,应该将其作为被采纳的答案。 - g4ost
很高兴能帮助@GeorgeGarey。 - GuRu
1
非常有帮助! - N. Dias
1
感谢 @N.Dias。 - GuRu

35

这是最终可工作的示例

<? include('application.php'); 
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'XX@XX.com';
$password = 'XX';

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

/* grab emails */
$emails = imap_search($inbox, 'FROM "xxx@gmail.com"');



/* if emails are returned, cycle through each... */
if($emails) {

  /* begin output var */
  $output = '';

  /* put the newest emails on top */
  rsort($emails);




    foreach($emails as $email_number) {

    /* get information specific to this email */
    $overview = imap_fetch_overview($inbox,$email_number,0);
    $message = imap_fetchbody($inbox,$email_number,2);
    $structure = imap_fetchstructure($inbox,$email_number);


    pre($overview);


     $attachments = array();
       if(isset($structure->parts) && count($structure->parts)) {
         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($inbox, $email_number, $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']);
             }
           }             
         } // for($i = 0; $i < count($structure->parts); $i++)
       } // if(isset($structure->parts) && count($structure->parts))


    if(count($attachments)!=0){
        foreach($attachments as $at){
            if($at['is_attachment']==1){
                file_put_contents($at['filename'], $at['attachment']);
            }
        }
    }

  }

 // echo $output;
} 

/* close the connection */
imap_close($inbox);

?>

1
我尝试过这个代码:“$attachments [$i]['attachment']”在使用 imap_fetchbody ($inbox, $email_number, $i + 1) 后总是为空 - 数组中有名字,但附件键中没有任何内容。为什么会这样? - cukabeka
你能提供一下你使用的imap类的链接吗? - Hassan-Zahid

2
一些关于已经完美工作的答案的错误修复和改进
$structure = imap_fetchstructure($mailbox, $email_number);
$attachments = [];

foreach ($structure->parts as $part) {
    $is_attachment = (isset($part->disposition) && $part->disposition == 'ATTACHMENT');

    if ($part->ifdparameters) {
        foreach ($part->dparameters as $object) {
            if (strtolower($object->attribute) == 'filename') {
                $is_attachment = true;
                $filename = $object->value;
                break;
            }
        }
    }

    if ($part->ifparameters) {
        foreach ($part->parameters as $object) {
            if (strtolower($object->attribute) == 'name') {
                $is_attachment = true;
                $name = $object->value;
                break;
            }
        }
    }

    if (!$is_attachment) {
        continue;
    }
    
    $attachment = imap_fetchbody($mailbox, $email_number, $email_number+1);

    if ($part->encoding == 3) {
        $attachment = base64_decode($attachment);
    } elseif ($part->encoding == 4) {
        $attachment = quoted_printable_decode($attachment);
    }

    $attachments[] = [
        'is_attachment' => $is_attachment,
        'filename' => isset($filename) ? $filename : '',
        'name' => isset($name) ? $name : '',
        'attachment' => isset($attachment) ? $attachment : ''
    ];
}


/* iterate through each attachment and save it */
$folder = "attachment";
if (!is_dir($folder)) {
         mkdir($folder);
    }

foreach ($attachments as $attachment) {

    if (!empty($attachment['name'])) {
        $filename = $attachment['name'];
    } elseif (!empty($attachment['filename'])) {
        $filename = $attachment['filename'];
    } else {
        $filename = time().'.dat';
    }

    $destination = './'.$folder.'/'.$email_number.'-'.$filename;

    file_put_contents($destination, $attachment['attachment']);
}

  • count函数在输入为falsy时返回1(真值),因此不应在比较中使用它
  • 当您可以使用foreach时,您不需要使用循环for:使事情变得简单
  • 仅在实际有用时将新项目添加到数组附件中:添加稍后将被跳过的项目是没有意义的
  • foreach循环遍历可迭代对象,如果计数为0,则不会循环:无需在foreach之前检查计数
  • 无需分配$filename并覆盖:只需通过比较检查,并直接分配适当的值或默认情况
  • file_put_contents与依次调用fopen()fwrite()fclose()相同,用于将数据写入文件
  • $is_attachment的检查更加健壮
  • mkdir文件夹应该在循环外,因为文件夹始终相同

2

看看这段代码:

           $structure = imap_fetchstructure($mailbox, $index);

       $attachments = array();
       if(isset($structure->parts) && count($structure->parts)) {
         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($connection, $message_number, $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']);
             }
           }             
         } // for($i = 0; $i < count($structure->parts); $i++)
       } // if(isset($structure->parts) && count($structure->parts))

-1
    //may this help you...good luck
    date_default_timezone_set('UTC');
    error_reporting(E_ALL);
    ini_set('display_errors', '1');     
    ini_set('memory_limit', '-1');     
    ini_set('max_execution_time', 0); 
    set_time_limit(3000); 
    $fName = [];
    if ($subject=='xyz subject' || $subject=='xyz subject')$folder_name = $subject;
    else$folder_name = substr($subject,stripos($subject,':')+2);
    $list = glob('downloads/xyz/'.$folder_name.'/*');
    foreach($list as  $key => $filename){$explodeName = explode('/', $filename);$fName[] = $explodeName[2];}
    foreach($list as $file){if(is_file($file))unlink($file);}     

    $hostname = '{imap.gmail.com:993/imap/ssl}Inbox';
    $username = 'xyz.xyz@xyz.com';
    $password = '*******************';

    $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());  
    $emails   = imap_search($inbox, 'SUBJECT "'.$subject.'"');
    foreach ($emails as $key => $value) {

        $overview = imap_fetch_overview($inbox,$value,0);
        $message_date = new DateTime($overview[0]->date);
        $date = $message_date->format('Ymd');
        $message = imap_fetchbody($inbox,$value,2);
        $structure = imap_fetchstructure($inbox, $value);
        $attachments = [];
        if(isset($structure->parts) && count($structure->parts)) 
        {
            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($inbox, $value, $i+1);                           
                    if($structure->parts[$i]->encoding == 3) //3 = BASE64 encoding
                    { 
                        $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                    }
                    elseif($structure->parts[$i]->encoding == 4) //4 = QUOTED-PRINTABLE encoding
                    { 
                        $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                    }
                }
            }
            foreach($attachments as $attachment)//iterate through each attachment and save it
            {
                if($attachment['is_attachment'] == 1)
                {
                    $filename = $attachment['name'];                        
                    if(empty($filename)) $filename = $attachment['filename'];
                    if(empty($filename)) $filename = time() . ".dat";
                    $new_fileName = $date.'-'.$value.'-'.$filename;                        
                    if(!in_array($new_fileName, $fName))
                    {
                        $folder='./downloads/xyz/'.$folder_name.'/';
                        if(!is_dir($folder))mkdir($folder);
                        $fp = fopen("./". $folder ."/". $date . "-". $value."-". $filename, "w+");
                        fwrite($fp, $attachment['attachment']);
                        fclose($fp);
                    }
                }
            }
        }
        imap_mail_move($inbox,$overview[0]->msgno,'xyz_label'); 
        imap_expunge($inbox); 

        /*  ->Always try to read/open the email by subject/or according to need
            ->Move or Delete Old/not required mail, so that u don't need to search/load lots of email
            ->Avoiding unnecessary and old email of the same subject , is to move/delete the same.
        */
    }
    imap_close($inbox);//Never forget to close the connection

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接