【问题标题】:Fetching attachments from gmail via either python or php通过 python 或 php 从 gmail 获取附件
【发布时间】:2008-11-23 08:03:16
【问题描述】:

我一直在尝试查找有关如何在 python 或 PHP 中从 gmail 帐户中检索附件的信息,希望这里有人可以提供帮助,谢谢。

相关:

【问题讨论】:

  • 我添加了“如何从 Gmail 下载所有带有附件的电子邮件?”的链接

标签: php python gmail attachment


【解决方案1】:

您必须启用对您的 GMail 帐户的 IMAP 访问(设置 → 转发和 POP/IMAP),然后使用imaplib.IMAP4_SSL 访问它。

使用每封邮件的原始文本作为email.message_from_string 的参数,以便处理任何附件。

【讨论】:

    【解决方案2】:

    我采用了上面的代码并对其进行了修复和测试。它适用于 PHP5。

    <?php 
    
    $gmail_username = 'email@gmail.com';
    $gmail_password = 'password';
    $imap = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $gmail_username, $gmail_password) or die("can't connect: " . imap_last_error());
    $savefilepath = '//Server/share/Local/Pathname/'; //absolute path to images directory
    $imagefilepath = '/Local/Pathname/'; //relative path to images directory
    $savethumbpath = '/Local/Pathname/'; //relative path to images directory
    $headers = imap_headers($imap);
    foreach ($headers as $mail) {
        $flags = substr($mail, 0, 4);
        //Check for unread msgs, get their UID, and queue them up
        if (strpos($flags, "U")) {
            preg_match('/[0-9]+/',$mail,$match);
            $new_msg[] = implode('',$match);     
        }
    }
    if ($new_msg) {
        foreach ($new_msg as $result) {
            $structure = imap_fetchstructure($imap,$result);
            $parts = $structure->parts;
            foreach ($parts as $part) {
                if ($part->parameters[0]->attribute == "NAME") {
                    //Generate a filename with format DATE_RANDOM#_ATTACHMENTNAME.EXT
                    $savefilename = date("m-d-Y") . '_' . rand() . '_' . $part->parameters[0]->value;
                       save_attachment(imap_fetchbody($imap,$result,2),$savefilename,$savefilepath,$savethumbpath);
                    imap_fetchbody($imap,$result,2); //This marks message as read
                } 
            }
        }
    }
    /* grab emails */
    $emails = imap_search($imap,'ALL');
    /* if emails are returned, cycle through each... */
    if($emails) {
      /* put the newest emails on top */
      $total = imap_num_msg($imap);
      /* for every email... */
      for( $i = $total; $i >= 1; $i--) {
            $headers = imap_header($imap, $i);
            $from = $headers->from[0]->mailbox . "@" . $headers->from[0]->host;
            echo $from . "\n";
            imap_delete($imap,$i);
            imap_mail_move($imap,"$i:$i", "[Gmail]/Trash"); // Change or remove this line if you are not connecting to gmail. The path to the Trash folder in your Gmail may be different, capitalization is relevant.
      }
    }else{
            echo "no emails";
    }
    /* close the connection */
       imap_expunge($imap);
       imap_close($imap);
    
    function save_attachment( $content , $filename , $localfilepath, $thumbfilepath ) {
         if (imap_base64($content) != FALSE) {   
             $file = fopen($localfilepath.$filename, 'w');
             fwrite($file, imap_base64($content));
             fclose($file);
         }
    }
    ?>
    

    【讨论】:

      【解决方案3】:

      我发现了一些有效的代码!这会将所有附件下载到选定的文件夹

      <?php 
      
      $gmail_username = 'username@gmail.com';
      $gmail_password = 'mypassword';
      
      $imap = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $gmail_username, $gmail_password) or die("can't connect: " . imap_last_error());
      $savefilepath = 'path/to/images_folder/'; //absolute path to images directory
      $imagefilepath = 'images/'; //relative path to images directory
      
      $headers = imap_headers($imap);
      foreach ($headers as $mail) {
          $flags = substr($mail, 0, 4);
          //Check for unread msgs, get their UID, and queue them up
          if (strpos($flags, "U")) {
              preg_match('/[0-9]+/',$mail,$match);
              $new_msg[] = implode('',$match);     
          }
      }
      
      if ($new_msg) {
          foreach ($new_msg as $result) {
              $structure = imap_fetchstructure($imap,$result);
              $parts = $structure->parts;
              foreach ($parts as $part) {
                  if ($part->parameters[0]->attribute == "NAME") {
                      //Generate a filename with format DATE_RANDOM#_ATTACHMENTNAME.EXT
                      $savefilename = date("m-d-Y") . '_' . mt_rand(rand(), 6) . '_' . $part->parameters[0]->value;
                      save_attachment(imap_fetchbody($imap,$result,2),$savefilename,$savefilepath,$savethumbpath);
                      imap_fetchbody($imap,$result,2); //This marks message as read
                  } 
              }
          }
      }
      
      imap_close($imap);
      
      function save_attachment( $content , $filename , $localfilepath, $thumbfilepath ) {
          if (imap_base64($content) != FALSE) {   
              $file = fopen($localfilepath.$filename, 'w');
              fwrite($file, imap_base64($content));
              fclose($file);
          }
      }
      ?>
      

      【讨论】:

        【解决方案4】:
        I recently worked on this topic and here is the code which works well. It also saves the details of the attachments in a word document with the following details:
        -> Date
        -> Time
        -> From
        -> Email ID
        -> Subject
        
        
        
        
        
        
        
        
        
        
        <?php 
        
        
         /*
            *   Gmail attachment extractor.
            *
            *   Downloads attachments from Gmail and saves it to a file.
            *   Uses PHP IMAP extension, so make sure it is enabled in your php.ini,
            *   extension=php_imap.dll
            *
            */
        
            header('Content-type:application\msword');
            header('Content-Disposition:attachment;Filename=document_name.doc');
            set_time_limit(0); 
            /* connect to gmail with your credentials */
            $hostname = '{imap.googlemail.com:993/imap/ssl}INBOX';
            $username = 'email@gmail.com';
            $password = 'password';
            /* try to connect */
            $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to       
            Gmail: ' . imap_last_error());
            /* get all new emails. If set to 'ALL' instead 
            * of 'NEW' retrieves all the emails, but can be 
            * resource intensive, so the following variable, 
            * $max_emails, puts the limit on the number of emails downloaded.
            * 
            */
            $emails = imap_search($inbox,'ALL');
            /* useful only if the above search is set to 'ALL' */
            $max_emails = 110;
        
        
            /* 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);
            $check=imap_check($inbox);
            $result=imap_fetch_overview($inbox,"1:{$check->Nmsgs}",0);
            foreach($result as $overview){
            echo "#{$overview->msgno}({$overview->date})-From: {$overview->from}
            {$overview->subject}\n"}
            /* get mail message */
            $message = imap_fetchbody($inbox,$email_number,2);
            /* get mail structure */
            $structure =imap_fetchstructure($inbox, $email_number);
            //$functions = array('function1' => imap_fetchstructure($inbox,
            $email_number));
            //print_r(array_keys($functions));
            $attachments = array();
            //print_r(array_keys($attachments[$i]));
            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);
             /* 4 = QUOTED-PRINTABLE encoding */
             if($structure->parts[$i]->encoding == 3){ 
             $attachments[$i]['attachment'] = base64_decode($attachments[$i]  
                   ['attachment']);
              }
              /* 3 = BASE64 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";
               /* prefix the email number to the filename in case two emails
               * have the attachment with the same file name.
               */
               $fp = fopen($email_number . "-" . $filename, "w+");
               fwrite($fp, $attachment['attachment']);
                fclose($fp);
                }
        
                }
        
                  if($count++ >= $max_emails) break;
        
        
                 }
        
               } 
        
                /* close the connection */
        
               imap_close($inbox);
        
          ?>
        

        【讨论】:

          【解决方案5】:

          imap_open 的 php 文档解释了在 cmets 中连接到 gmail(例如 2007 年 10 月 31 日 07:50):

          $mbox = imap_open("{imap.gmail.com:993/imap/ssl}INBOX", "username@gmail.com", "password") or die("can't connect: " . imap_last_error());

          显然,您必须根据需要填写实际的用户名和密码,然后按照以下说明识别电子邮件部分中的附件:http://www.electrictoolbox.com/extract-attachments-email-php-imap/

          总而言之,您使用的是:

          // in a for($i=1;$i<$nummsgs;$i++) loop over all the messages in the inbox $structure = imap_fetchstructure($mbox, $i);

          识别结构中的附件。但是,这是一个相当复杂的 MIME 消息解构过程(必须考虑到许多可选的可变性),因此该功能的基本原理/概述在该电动工具箱页面中。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-05-16
            • 2013-02-06
            • 2013-08-01
            • 1970-01-01
            • 2017-06-20
            • 2012-09-23
            • 1970-01-01
            • 2017-08-09
            相关资源
            最近更新 更多