title: Post to blog via E-mail PHP
body: <p>I'm building a simple blog platform. The person I'm building this for is blind and has asked for a solution. He's suggested that as he is already capable of using outlook it'd be good if he could just email a specific email address and it automatically inserts to the db.</p>
  
  <p>Here is what I have so far (i'm using a cronjob to execute this script every 10 minutes):</p>
  
  <pre><code>        include('Imap.php');
  
      $date = date('d-M-y', strtotime('1 day ago'));
      $term = 'ALL UNDELETED SINCE "'.$date.'"';
  
      //ignore array of emails
      $exclude = [];
  
     $email    = 'email@email.com'
    $password = 'mypassword';
  $host     = 'mymailhost'//your email host
  $port     = '0000'//port number
  $savePath = "emails";//folder to save attachments
  $delete   = true;//set to true to delete email
  
  //initialise email
  $imap = new Imap($email, $password,$host,$port, 'Inbox', $savePath, $delete);
  
  //get emails pass in the search term and exclude array
  $emails = $imap-&gt;emails($term, $exclude);
  
  foreach($emails as $email)
  {
  $stmt = $db-&gt;prepare('INSERT INTO blog_posts (postTitle,
  postDesc,postCont,postDate) VALUES  (:postTitle, :postDesc, :postCont, 
  :postDate)') ;
  $stmt-&gt;execute(array(
      ':postTitle' =&gt; $email['subject'],
      ':postDesc' =&gt; substr($email['body'], 0, 200),
      ':postCont' =&gt; $email['body'],
      ':postDate' =&gt; date('Y-m-d H:i:s')
   ));
   }
  </code></pre>
  
  <p>I also have an Imap class:</p>
  
  <pre><code>&lt;?php
  class Imap {
  private $imap;
  private $email;
  private $folder;
  private $host;
  private $port;
  private $secure;
  private $connection;
  private $saveFolder;
  private $delete;
  public function __construct($email, $password, $host, $port, $folder, $saveFolder, $delete = false)
  {
      $this-&gt;email      = $email;
      $this-&gt;host       = $host;
      $this-&gt;port       = $port;
      $this-&gt;folder     = $folder;
      $this-&gt;saveFolder = $saveFolder;
      $this-&gt;delete     = $delete;
      // Connect to a remote imap server
      if ($port != '143') {
          $this-&gt;secure = 'ssl/';
      }
      $this-&gt;connection = "{{$host}:{$port}/imap/{$this-&gt;secure}novalidate-cert}$folder";
      $this-&gt;imap       = imap_open($this-&gt;connection, $email, $password);
      $accountPath = $this-&gt;saveFolder.'/'.$email;
      //create folder for email account
      if (!file_exists($accountPath)) {
          mkdir($accountPath);
      }
  }
  public function getFolders()
  {
      if ($this-&gt;imap) {
          $folderslist = imap_list($this-&gt;imap, $this-&gt;connection, "*");
          $folders     = [];
          if (is_array($folderslist)) {
              foreach ($folderslist as $folder) {
                  $folder = str_replace($this-&gt;connection, '', $folder);
                  $folders[] = $folder;
              }
          }
          return $folders;
      }
  }
  public function decode_utf8($string)
  {
      if (preg_match("@=\?.{0,}\?[Bb]\?@",$string)) {
          $string = preg_split("@=\?.{0,}\?[Bb]\?@",$string);
          while (list($key, $value) = each($string)) {
              if (preg_match("@\?=@", $value)) {
                  $arrTemp    = preg_split("@\?=@", $value);
                  $arrTemp[0] = base64_decode($arrTemp[0]);
                  $string[$key]  = join("", $arrTemp);
              }
          }
          $string = join("", $string);
      }
      if (preg_match("@=\?.{0,}\?Q\?@", $string)) {
          $string = quoted_printable_decode($string);
          $string = preg_replace("/=\?.{0,}\?[Qq]\?/", "", $string);
          $string = preg_replace("/\?=/", "", $string);
      }
      return trim($string);
  }
  private function is_in_array($needle, $haystack)
  {
      foreach ($needle as $stack) {
          if (in_array(strtolower($stack), $haystack)) {
               return true;
          }
      }
      return false;
  }
  public function emails($searchterms, $exclude)
  {
      $search = imap_search($this-&gt;imap, $searchterms);
      if (is_array($search)) {
          /* put the newest emails on top */
          rsort($search);
          $data = [];
          foreach ($search as $msg_id) {
              $check = array();
              $header = imap_header($this-&gt;imap, $msg_id);
              $subject = $header-&gt;subject;
              $msgno   = $header-&gt;Msgno;
              $from    = $header-&gt;from;
              $date    = $header-&gt;udate;
              $to      = $header-&gt;to;
              if(array_key_exists('cc', $header)) {
                  $cc  = $header-&gt;cc;
              } else {
                  $cc = null;
              }
              $fromaddress = null;
              $toaddress = null;
              $ccaddress = null;
              if (is_array($from)) {
                  foreach ($from as $id =&gt; $object) {
                      $fromname = $object-&gt;personal;
                      $fromaddress.= $object-&gt;mailbox . "@" . $object-&gt;host;
                      $check[] = strtolower($object-&gt;mailbox . "@" . $object-&gt;host);
                  }
              }
              if (is_array($to)) {
                  foreach ($to as $id =&gt; $object) {
                      $toaddress.= $object-&gt;mailbox . "@" . $object-&gt;host.' ';
                      $check[] = strtolower($object-&gt;mailbox . "@" . $object-&gt;host);
                  }
              }
              if (is_array($cc)) {
                  foreach ($cc as $id =&gt; $object) {
                      $ccaddress.= $object-&gt;mailbox . "@" . $object-&gt;host.' ';
                      $check[] = strtolower($object-&gt;mailbox . "@" . $object-&gt;host);
                  }
              }
              $target = array(
                  strtolower($this-&gt;email),
                  strtolower($fromaddress),
                  strtolower($toaddress),
                  strtolower($ccaddress)
              );
              $path = $this-&gt;saveFolder.'/'.$this-&gt;email.'/'.$msgno.'/';
              //if not in the exclude array insert
              if($this-&gt;is_in_array($exclude, $target) == false &amp;&amp; $this-&gt;is_in_array($exclude, $check) == false){
                  $body = $this-&gt;getBody($msg_id);
                  $data[] = [
                      'account'     =&gt; $this-&gt;email,
                      'folder'      =&gt; $this-&gt;folder,
                      'subject'     =&gt; $this-&gt;decode_utf8($subject),
                      'msgno'       =&gt; $msgno,
                      'emailDate'   =&gt; date('Y-m-d H:i:s', $date),
                      'fromName'    =&gt; $fromname,
                      'fromAddress' =&gt; $fromaddress,
                      'toAddress'   =&gt; $toaddress,
                      'ccAddress'   =&gt; $ccaddress,
                      'body'        =&gt; $this-&gt;getBody($msg_id),
                      'attachments' =&gt; $this-&gt;getAttachments($msg_id)
                  ];
                  if ($this-&gt;delete == true) {
                      imap_delete($this-&gt;imap, $msg_id); //mark for deletion
                      imap_expunge($this-&gt;imap); //delete all marked for deletion
                  }
                  //if($header-&gt;Recent == 'Y'){
                     //mark email as unread
                      //imap_clearflag_full($this-&gt;imap, $msg_id, "\\Seen");
                  //}
              }
          }
          return $data;
      }
  }
  public function getBody($uid) {
      $body = $this-&gt;get_part($uid, "TEXT/HTML");
      // if HTML body is empty, try getting text body
      if ($body == "") {
          $body = $this-&gt;get_part($uid, "TEXT/PLAIN");
      }
      //store email account to local variable
      $email = $this-&gt;email;
      //replace cid with full path to image
      $body = preg_replace_callback(
          '/src="cid:(.*)"&gt;/Uims',
          function($m) use($email, $uid){
              //split on @
              $parts = explode('@', $m[1]);
              //replace local path with absolute path
              $img = str_replace($parts[0], resource_url($email.'/'.$uid.'/'.$parts[0], 'Emails'), $parts[0]);
              return "src='$img'&gt;";
         },
      $body);
      return trim(utf8_encode(quoted_printable_decode($body)));
  }
  public function getAttachments($uid) {
      $attachments = [];
      $info = imap_fetchstructure($this-&gt;imap, $uid);
      if (isset($info-&gt;parts)) {
          $i = 0;
          foreach ($info-&gt;parts as $part) {
              $path = $this-&gt;saveFolder.'/'.$this-&gt;email.'/'.$uid.'/';
              if (array_key_exists('disposition', $part)) {
                  //create folder for email account
                  if (!file_exists($path)) {
                      mkdir($path);
                  }
                  if (strtolower($part-&gt;disposition) == "inline") {
                      $this-&gt;save_inline_image($info, $i, $uid, $path);
                  }
                  if (strtolower($part-&gt;disposition) == "attachment") {
                      $attachments[] = $this-&gt;save_attachment($info, $i, $uid, $path);
                  }
              } elseif(isset($part-&gt;parts)) {
                  foreach ($part-&gt;parts as $linepart) {
                      if (array_key_exists('disposition', $part)) {
                          //create folder for email account
                          if (!file_exists($path)) {
                              mkdir($path);
                          }
                          if (strtolower($part-&gt;disposition) == "inline") {
                              $this-&gt;save_inline_image($info, $i, $uid, $path);
                          }
                          if (strtolower($part-&gt;disposition) == "attachment") {
                              $attachments[] = $this-&gt;save_attachment($info, $i, $uid, $path);
                          }
                      }
                  }
              }
          $i++;}
      }
      return $attachments;
  }
  private function save_inline_image($structure, $k, $mid, $path)
  {
      if (isset($structure-&gt;parts[$k]-&gt;dparameters[0])) {
          //extract file name from headers
          $fileName = strtolower($structure-&gt;parts[$k]-&gt;dparameters[0]-&gt;value);
          //extract attachment from email body
          $fileSource = base64_decode(imap_fetchbody($this-&gt;imap, $mid, $k+1, FT_PEEK));
          if (!is_dir($path)) {
            // dir doesn't exist, make it
            mkdir($path);
          }
          $file = $path.$fileName;
          //only save if file does not exist
          if(!file_exists($file) &amp;&amp; $fileName !=''){
              file_put_contents($file, $fileSource);
          }
      }
  }
  private function save_attachment($structure, $k, $mid, $path)
  {
      //extract file name from headers
      $fileName = strtolower($structure-&gt;parts[$k]-&gt;dparameters[0]-&gt;value);
      $file = $path.$fileName;
      $mege = imap_fetchbody($this-&gt;imap, $mid, $k+1, FT_PEEK);
      $fp   = fopen($file, 'w');
      $data = $this-&gt;getdecodevalue($mege,$structure-&gt;parts[$k]-&gt;type);
      fwrite($fp, $data);
      fclose($fp);
      return [
          'account'  =&gt; $this-&gt;email,
          'msgno'    =&gt; $mid,
          'file'     =&gt; $file,
          'fileName' =&gt; $fileName
      ];
  }
  private function getdecodevalue($message,$coding) {
    switch($coding) {
        case 0:
        case 1:
            //$message = imap_8bit($message);
            $message = imap_base64($message);
            break;
        case 2:
            $message = imap_binary($message);
            break;
        case 3:
        case 5:
            $message = imap_base64($message);
            break;
        case 4:
            $message = imap_qprint($message);
            break;
    }
    return $message;
  }
  private function get_part($uid, $mimetype, $structure = false, $partNumber = false) {
      if (!$structure) {
             $structure = imap_fetchstructure($this-&gt;imap, $uid);
      }
      if ($structure) {
          if ($mimetype == $this-&gt;get_mime_type($structure)) {
              if (!$partNumber) {
                  $partNumber = 1;
              }
              $text = imap_fetchbody($this-&gt;imap, $uid, $partNumber, FT_PEEK);
              switch ($structure-&gt;encoding) {
                  # 7BIT
                  case 0:
                      return imap_qprint($text);
                  # 8BIT
                  case 1:
                      return imap_8bit($text);
                  # BINARY
                  case 2:
                      return imap_binary($text);
                  # BASE64
                  case 3:
                      return imap_base64($text);
                  # QUOTED-PRINTABLE
                  case 4:
                      return quoted_printable_decode($text);
                  # OTHER
                  case 5:
                      return $text;
                  # UNKNOWN
                  default:
                      return $text;
              }
         }
          // multipart
          if ($structure-&gt;type == 1) {
              foreach ($structure-&gt;parts as $index =&gt; $subStruct) {
                  $prefix = "";
                  if ($partNumber) {
                      $prefix = $partNumber . ".";
                  }
                  $data = $this-&gt;get_part($uid, $mimetype, $subStruct, $prefix . ($index + 1));
                  if ($data) {
                      return $data;
                  }
              }
          }
      }
      return false;
  }
  private function get_mime_type($structure) {
      $primaryMimetype = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
      if ($structure-&gt;subtype) {
         return $primaryMimetype[(int)$structure-&gt;type] . "/" . $structure-&gt;subtype;
      }
      return "TEXT/PLAIN";
  }
  public function numEmails()
  {
      if ($this-&gt;imap) {
          return imap_num_msg($this-&gt;imap);
      }
  }
  public function __destruct()
  {
      if ($this-&gt;imap) {
          imap_errors();
          imap_alerts();
          imap_close($this-&gt;imap);
      }
  }
  }
  </code></pre>
  
  <p>I also have a config.php file with my db connection stuff in. I can't get it to work </p>
  
  <p>I'm a beginner and would love some help please.</p>
  
  <p>UPDATE:</p>
  
  <p>So I've managed to fix a few errors. I'm now getting output via the cron job. Here is the latest:</p>
  
  <pre><code>Set-Cookie: PHPSESSID=7af70fe141699e99f62b6473588acbbf; path=/
  
  Expires: Thu, 19 Nov 1981 08:52:00 GMT
  Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
  Pragma: no-cache
  Content-type: text/html
  
  &lt;br /&gt;
  &lt;b&gt;Warning&lt;/b&gt;:  Invalid argument supplied for foreach()
  in &lt;b&gt;/home/mysite/public_html/blog/import.php&lt;/b&gt; on line
  &lt;b&gt;24&lt;/b&gt;&lt;br /&gt;
  </code></pre>
  
  <p>I'm unable to get past the error above. I've used google and stack search but I can't find specific results.</p>
  
  <p>Thanks.</p>