Wednesday, July 21, 2010

Download gmail attachment in PHP

Download gmail attachment in PHP

If you want to download gmail attachment by PHP code?,  then here is the code that will do it.
just copy and paste the entire code and run it.



<?php
class ImapMail
{
    var $dirPath,$deleteEmails=false;
    var $imapInBox;
    function __construct($mailHost,$emailLogin,$pass) {
        $this->imapInBox=imap_open($mailHost,$emailLogin,$pass) or die("Unable to connect:".imap_last_error());
    }
    function getdecodevalue($msg,$bodyType) {
        if($bodyType==0 || $bodyType==1) {
            $msg = imap_base64($msg);
        }
        if($bodyType==2) {
            $msg = imap_binary($msg);
        }
        if($bodyType==3 || $bodyType==5) {
            $msg = imap_base64($msg);
        }
        if($bodyType==4) {
            $msg = imap_qprint($msg);
        }
        return $msg;
    }

    function downLoadAttachment($dirPath,$deleteEmails=false) {
        $nAttachment = 0;
        $dirPath = str_replace('\\', '/', $dirPath);
        if (substr($dirPath, strlen($dirPath) - 1) != '/') {
            $dirPath .= '/';
        }
        $message = array();
        $message["attachment"]["type"][0] = "text";
        $message["attachment"]["type"][1] = "multipart";
        $message["attachment"]["type"][2] = "message";
        $message["attachment"]["type"][3] = "application";
        $message["attachment"]["type"][4] = "audio";
        $message["attachment"]["type"][5] = "image";
        $message["attachment"]["type"][6] = "video";
        $message["attachment"]["type"][7] = "other";
       
        $nEmails = imap_search($this->imapInBox, 'ALL', SE_UID);
        $j=-1;
        for ($j = 0; $j < count($nEmails); $j++) {
            $j++;
            $messStructure = imap_fetchstructure($this->imapInBox, $nEmails[$j] , FT_UID);
            $overview = imap_fetch_overview($this->imapInBox,$j ,0);
        echo '<span>Read/Unread'.($overview[0]->seen ? 'read' : 'unread').'</span>';
        echo  '<span>Subject:: '.$overview[0]->subject.'</span> ';
        echo  '<span>From:: '.$overview[0]->from.'</span>';
        echo '<span>On:: '.$overview[0]->date.'</span>';
            $body = imap_fetchbody($this->imapInBox,$j ,2);
            echo $body;
            if(isset($messStructure->parts)) {
                $parts = $messStructure->parts;
                $fpos=2;
                for($i = 1; $i < count($parts); $i++) {
                $message["pid"][$i] = ($i);
                $part = $parts[$i];
                if(isset($part->disposition) && $part->disposition == "ATTACHMENT") {
                    $message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
                    $message["subtype"][$i] = strtolower($part->subtype);
                    $fileName=$part->dparameters[0]->value;
                    $mess = imap_fetchbody($this->imapInBox,$j+1,$fpos); 
                    $fp=fopen($dirPath.$fileName, 'w');
                    $data=$this->getdecodevalue($mess,$part->type);   
                    fwrite($fp,$data);
                    fclose($fp);
                    $nAttachment++;
                    $fpos+=1;
                }
            }
                if ($this->deleteEmails) {
                    //imap_delete($this->imapInBox,$j+1);
                }
            }
        }
        if ($this->deleteEmails) {
            //imap_expunge($this->imapInBox);
        }
        imap_close($this->imapInBox);
        return ("Completed ($nAttachment attachment(s) downloaded into $dirPath)");
    }
}

$mailHost="{imap.gmail.com:993/imap/ssl}INBOX";
$emailLogin="FULL-GMAIL-ID-HERE";
$pass="PASSWORD-HERE";
$dirPath=$_SERVER['DOCUMENT_ROOT']."test/gmail/";
$deleteEmails=false;
$mailObj=new ImapMail($mailHost,$emailLogin,$pass);
echo $mailObj->downLoadAttachment($dirPath,$deleteEmails=false);
?>




3 comments:

  1. Hello Amit,
    i tried your code for GMAIL IMAP to download attachment works like charm but problem is with code is as i tried to get attachment from particular email with
    $nEmails = imap_search($this->imapInBox, 'FROM anymail@gmail.com', SE_UID);
    it gives me nothing with no errors, but i am sure there are attachment for same emails id i been using

    ReplyDelete
  2. Milind,

    Try to use user name for example 'FROM "Milind"' with From clause
    ***Note that name must be in double quotes as listed below:

    $nEmails=imap_search($this->imapInBox,'FROM "Milind"', SE_UID);

    ReplyDelete
  3. Thanks Amit double quotes worked for me !

    ReplyDelete