Matt_
Matt_

Reputation: 43

using PHP to read email attachment (csv)

I've got an application that I don't think I can interact via an API with. All it can do is export data in csv format as a one off download or have reports emailed as csv to an email.

I want to make some sexy graphs with the data but don't want to have to manually download and input csv data each time I need to generate reports (monthly).

I was thinking, create a basic email account, send the csv reports as email attachments monthly to that and have a php cli script run in cron each month to login and extract the csv information from the attachments.

Sound possible? I know how to send email via php but what libraries do I use to open email and read attachments?

Upvotes: 1

Views: 6665

Answers (1)

Abhinav
Abhinav

Reputation: 408

<?php  
 // Standard inclusions     
 include("pChart/pData.class");  
 include("pChart/pChart.class");  

 // Dataset definition   
 $DataSet = new pData;  
 $DataSet->ImportFromCSV("Sample/CO2.csv",",",array(1,2,3,4),TRUE,0);  
 $DataSet->AddAllSeries();  
 $DataSet->SetAbsciseLabelSerie();  
 $DataSet->SetYAxisName("CO2 concentrations");  

 // Initialise the graph  
 $Test = new pChart(700,230);  
 $Test->reportWarnings("GD");  
 $Test->setFontProperties("Fonts/tahoma.ttf",8);  
 $Test->setGraphArea(60,30,680,180);  
 $Test->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
 $Test->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
 $Test->drawGraphArea(255,255,255,TRUE);  
 $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,90,2);  
 $Test->drawGrid(4,TRUE,230,230,230,50);  

 // Draw the 0 line  
 $Test->setFontProperties("Fonts/tahoma.ttf",6);  
 $Test->drawTreshold(0,143,55,72,TRUE,TRUE);  

 // Draw the line graph  
 $Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());  
 $Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),3,2,255,255,255);  

 // Finish the graph  
 $Test->setFontProperties("Fonts/tahoma.ttf",8);     
 $Test->drawLegend(70,40,$DataSet->GetDataDescription(),255,255,255);     
 $Test->setFontProperties("Fonts/tahoma.ttf",10);  
 $Test->drawTitle(60,22,"CO2 concentrations at Mauna Loa",50,50,50,585);  
 $Test->Render("example16.png");     
?>

And you can download this pluggin from http://pchart.sourceforge.net/download.php

And you can view full documentation http://pchart.sourceforge.net/documentation.php

And this is the code for saving attachment from mail to folder.

<?php

set_time_limit(3000); 

/* connect to gmail with your credentials */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'YOUR_USERNAME'; 
$password = 'YOUR_PASSWORD';

/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

$emails = imap_search($inbox, 'FROM "[email protected]"');

/* 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);

        $message = imap_fetchbody($inbox,$email_number,2);

        /* get mail structure */
        $structure = imap_fetchstructure($inbox, $email_number);

        $attachments = array();

        /* if any attachments found... */
        if(isset($structure->parts) && count($structure->parts)) 
        {
            for($i = 0; $i < count($structure->parts); $i++) 
            {
                $attachments[$i] = array(
                    'is_attachment' => false,
                    'filename' => '',
                    'name' => '',
                    'attachment' => ''
                );

                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);

                    /* 3 = BASE64 encoding */
                    if($structure->parts[$i]->encoding == 3) 
                    { 
                        $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                    }
                    /* 4 = QUOTED-PRINTABLE 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";
                $folder = "attachment";
                if(!is_dir($folder))
                {
                     mkdir($folder);
                }
                $fp = fopen("./". $folder ."/". $email_number . "-" . $filename, "w+");
                fwrite($fp, $attachment['attachment']);
                fclose($fp);
            }
        }
    }
} 

/* close the connection */
imap_close($inbox);

echo "all attachment Downloaded";

?>

And for more details visit http://www.codediesel.com/php/downloading-gmail-attachments-in-php-an-update/

Upvotes: 2

Related Questions