找回密码
 注册

QQ登录

只需一步,快速开始

查看: 222|回复: 0

Extracting Attachments From Emails With PHP

[复制链接]
发表于 2014-2-11 22:27:53 | 显示全部楼层 |阅读模式
本帖最后由 demo 于 2014-2-12 14:31 编辑

Yesterday I wrote about how to read emails with PHP, but I want to dig a bit deeper and discuss another part of the My Slow Low project that needed tackling: Extracting attachments from emails with PHP. For the purposes of this post, I will be specifically discussing file attachments, not HTML inline attached files.
This project was executed with CodeIgniter 2.0 so there are a few libraries and helper functions used that will not be available in other frameworks or with straight PHP, however, their functionality can be pretty easily replicated.
  1.         function email_pull() {
  2.             // load the Email_reader library from previous post
  3.             $this->load->library('email_reader');
  4.          
  5.             // load the meals_model to store meal information
  6.             $this->load->model('meals_model');
  7.          
  8.             // this method is run on a cronjob and should process all emails in the inbox
  9.             while (1) {
  10.                 // get an email
  11.                 $email = $this->email_reader->get();
  12.          
  13.                 // if there are no emails, jump out
  14.                 if (count($email) <= 0) {
  15.                     break;
  16.                 }
  17.          
  18.                 $attachments = array();
  19.                 // check for attachments
  20.                 if (isset($email['structure']->parts) && count($email['structure']->parts)) {
  21.                     // loop through all attachments
  22.                     for ($i = 0; $i < count($email['structure']->parts); $i++) {
  23.                         // set up an empty attachment
  24.                         $attachments[$i] = array(
  25.                             'is_attachment' => FALSE,
  26.                             'filename'      => '',
  27.                             'name'          => '',
  28.                             'attachment'    => ''
  29.                         );
  30.          
  31.                         // if this attachment has idfparameters, then proceed
  32.                         if ($email['structure']->parts[$i]->ifdparameters) {
  33.                             foreach ($email['structure']->parts[$i]->dparameters as $object) {
  34.                                 // if this attachment is a file, mark the attachment and filename
  35.                                 if (strtolower($object->attribute) == 'filename') {
  36.                                     $attachments[$i]['is_attachment'] = TRUE;
  37.                                     $attachments[$i]['filename']      = $object->value;
  38.                                 }
  39.                             }
  40.                         }
  41.          
  42.                         // if this attachment has ifparameters, then proceed as above
  43.                         if ($email['structure']->parts[$i]->ifparameters) {
  44.                             foreach ($email['structure']->parts[$i]->parameters as $object) {
  45.                                 if (strtolower($object->attribute) == 'name') {
  46.                                     $attachments[$i]['is_attachment'] = TRUE;
  47.                                     $attachments[$i]['name']          = $object->value;
  48.                                 }
  49.                             }
  50.                         }
  51.          
  52.                         // if we found a valid attachment for this 'part' of the email, process the attachment
  53.                         if ($attachments[$i]['is_attachment']) {
  54.                             // get the content of the attachment
  55.                             $attachments[$i]['attachment'] = imap_fetchbody($this->email_reader->conn, $email['index'], $i+1);
  56.          
  57.                             // check if this is base64 encoding
  58.                             if ($email['structure']->parts[$i]->encoding == 3) { // 3 = BASE64
  59.                                 $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
  60.                             }
  61.                             // otherwise, check if this is "quoted-printable" format
  62.                             elseif ($email['structure']->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
  63.                                 $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
  64.                             }
  65.                         }
  66.                     }
  67.                 }
  68.          
  69.                 // for My Slow Low, check if I found an image attachment
  70.                 $found_img = FALSE;
  71.                 foreach ($attachments as $a) {
  72.                     if ($a['is_attachment'] == 1) {
  73.                         // get information on the file
  74.                         $finfo = pathinfo($a['filename']);
  75.          
  76.                         // check if the file is a jpg, png, or gif
  77.                         if (preg_match('/(jpg|gif|png)/i', $finfo['extension'], $n)) {
  78.                             $found_img = TRUE;
  79.                             // process the image (save, resize, crop, etc.)
  80.                             $fname = $this->_process_img($a['attachment'], $n[1]);
  81.          
  82.                             break;
  83.                         }
  84.                     }
  85.                 }
  86.          
  87.                 // if there was no image, move the email to the Rejected folder on the server
  88.                 if ( ! $found_img) {
  89.                     $this->email_reader->move($email['index'], 'INBOX.Rejected');
  90.                     continue;
  91.                 }
  92.          
  93.                 // get content from the email that I want to store
  94.                 $addr   = $email['header']->from[0]->mailbox."@".$email['header']->from[0]->host;
  95.                 $sender = $email['header']->from[0]->mailbox;
  96.                 $text   = ( ! empty($email['header']->subject) ? $email['header']->subject : '');
  97.          
  98.                 // move the email to Processed folder on the server
  99.                 $this->email_reader->move($email['index'], 'INBOX.Processed');
  100.          
  101.                 // add the data to the database
  102.                 $this->meals_model->add(array(
  103.                     'username'    => $sender,
  104.                     'email'       => $addr,
  105.                     'photo'       => $fname,
  106.                     'description' => ($text == '' ? NULL : $text)
  107.                 ));
  108.          
  109.                 // don't slam the server
  110.                 sleep(1);
  111.             }
  112.          
  113.             // close the connection to the IMAP server
  114.             $this->email_reader->close();
  115.         }
复制代码
I tried to comment the code above as best as possible to convey what it is I am doing with the information. This code is a method within a Controller, but I’ve only included the attachment extraction method of the class for this post.
For more information and to credit those I’ve learned from, please check out David Walsh’s post on Retriev[ing] Your Gmail Emails with PHP and IMAP as well as Chris Hope’s post on Extracting attachments from an email message using PHP IMAP functions.


来自圈子: Demo俱乐部
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )

GMT-8, 2026-6-21 15:07 , Processed in 0.015025 second(s), 15 queries .

Supported by Weloment Group X3.5

© 2008-2026 Best Deal Online

快速回复 返回顶部 返回列表