Home > Programming > Read Gmail attachments with IMAP and PHP.

Read Gmail attachments with IMAP and PHP.

Recently I came up with the idea that I could use a Gmail account as a place holder to store pictures sent from my cell phone. The idea was that I could take a picture with my cell phone and it would instantly show up some where, such as a website or blog. The following code can be used to do this fairly easily. Simply create a Gmail account for testing purposes and use the following code to download and view the images from your Gmail account.

<?php
$save_path = "/tmp/";
$server = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX";
$login = "someaddress@gmail.com";
$password="SomePassword12345";

$mbox = imap_open($server, $login, $password) or die("can't connect: " . imap_last_error());
$count = imap_num_msg($mbox);

for($i = 1; $i <= $count; $i++) {
$message = $i;
$msg_header = imap_headerinfo($mbox,$message);

echo "From: " . $msg_header->fromaddress . '<br />';
echo $msg_header->subject . '<br />';
echo "Image CRC32:" . crc32($msg_header->message_id) . '<br />';

$info = imap_fetchstructure($mbox, $message);
$numparts = count($info->parts);
if ($numparts > 1) {
   $pcount=1;

   foreach ($info->parts as $part) {
      if ($part->subtype == "JPEG") {
        $filename = crc32($msg_header->message_id) . ".jpg";
         $binfile=imap_fetchbody($mbox,$message,2);
         savePic($filename,$binfile);
         echo "<img src='/sandbox/tmp/" . $filename . "' />";
      }elseif ($part->subtype == "PNG") {
         $filename = crc32($msg_header->message_id) . ".png";
         binfile=imap_fetchbody($mbox,$message,2);
         savePic($filename,$binfile);
         echo "<img src='/sandbox/tmp/" . $filename . "' />";

      }else{
          //echo "No attachment found.";
       }
     $pcount++;
   }

} else {
  //Do nothing.
}
}

function savePic($filename,$binfile)
{
global $save_path;
    $binfile = imap_base64($binfile);
     $fp=fopen($save_path. $filename,"w+");
      fwrite($fp,$binfile);
      fclose($fp);
    $image = new SimpleImage();
   $image->load($save_path. $filename);
   $image->resizeToWidth(450);
   $image->save($save_path. $filename);

}
Categories: Programming Tags: , ,
Digg: DIGG ME
  1. No comments yet.
  1. No trackbacks yet.