Read e-mail and extract attached files in my DB

Hi, i don’t know what i am doing wrong, i have this cron job: " php /home/public_html/mailing.php >/dev/null 2>&1" inside my hosting to make this file work but the system don’t register any file.

Thanks

[php]<?php
include(“readXML.php”);
include(“enviarMail.php”);

/**

  • Gmail attachment extractor.
  • Downloads attachments from Gmail and saves it to a file.
  • Uses PHP IMAP extension, so make sure it is enabled in your php.ini,
  • extension=php_imap.dll

*/

set_time_limit(3000);

/* connect to gmail with your credentials */
$hostname = ‘{imap.amanti.websitewelcome.com:993/imap/ssl}INBOX’;
$username = ‘[email protected]’; # e.g [email protected]
$password = ‘XXXX’;

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

/* get all new emails. If set to ‘ALL’ instead

  • of ‘NEW’ retrieves all the emails, but can be
  • resource intensive, so the following variable,
  • $max_emails, puts the limit on the number of emails downloaded.

/
$emails = imap_search($inbox,‘UNSEEN’);
//UNSEEN
/
useful only if the above search is set to ‘ALL’ */
$max_emails = 25;

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

	echo "Buscando email ";
    /* get information specific to this email */
    $overview = imap_fetch_overview($inbox,$email_number,0);


    /* get mail message */
    $message = imap_fetchbody($inbox,$email_number,2);

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

    $cabecera = imap_headerinfo($inbox, $email_number);

    $from = $cabecera->from;
    //echo print_r($cabecera->from);
    //echo print_r($from);
    //echo $from[0]->mailbox.'@'.$from[0]->host;
    $attachments = array();
    
    /* if any attachments found... */
    if(isset($structure->parts) && count($structure->parts)) 
    {
		echo "Si partes adjuntas ".count($structure->parts);
        for($i = 0; $i < count($structure->parts); $i++) 
        {
            $attachments[$i] = array(
                'is_attachment' => false,
                'filename' => '',
                'name' => '',
                'attachment' => ''
            );
        	echo "Array ".print_r($structure->parts[$i])."<br>";
			echo "Find ".$structure->parts[$i]->ifdparameters."<br>";
            if($structure->parts[$i]->ifdparameters) 
            {
				
                foreach($structure->parts[$i]->dparameters as $object) 
                {
					echo "Que regresa ".strtolower($object->attribute);
                    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);

                /* 4 = QUOTED-PRINTABLE encoding */
                if($structure->parts[$i]->encoding == 3) 
                { 
                    $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                }
                /* 3 = BASE64 encoding */
                elseif($structure->parts[$i]->encoding == 4) 
                { 
                    $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                }
            }
        }
    }
    
    /* iterate through each attachment and save it */
	$xml = "vacio";
	$pdf = "vacio";
    $xmlArray;
    $pdfArray;
    foreach($attachments as $attachment)
    {
        if($attachment['is_attachment'] == 1)
        {
            $filename = $attachment['name'];
			$ext = pathinfo($attachment['filename'], PATHINFO_EXTENSION);
			if(strtolower($ext)=="xml" || strtolower($ext)=="pdf"){
                //$extension = substr(strrchr($attachment['filename'], "."), 1);

                if(empty($filename)) $filename = $attachment['filename'];
                if(empty($filename)) $filename = time() . ".dat";
                $fp = fopen("./adjuntos/" . $email_number . "-" . strtolower($filename), "w+");
                fwrite($fp, $attachment['attachment']);
                fclose($fp);

                $finalName = "./adjuntos/" . $email_number . "-" . strtolower($filename);
               // echo $finalName;

                if(strtolower($ext)=="xml"){

                    //echo "Si encontre ".basename($attachment['filename'], ".".strtolower($ext));
                    $xmlArray[] = basename($finalName, ".".strtolower($ext));
                }else if(strtolower($ext)=="pdf"){
                    $pdfArray[] = basename($finalName, ".".strtolower($ext));
                }

				/*//Solo sacamos aquellos archivos que se llamen XML
				//echo "Size ".print_r($attachments);
                if(empty($filename)) $filename = $attachment['filename'];
                if(empty($filename)) $filename = time() . ".dat";
                $fp = fopen("./adjuntos/" . $email_number . "-" . $filename, "w+");
                fwrite($fp, $attachment['attachment']);
                fclose($fp);
				
				if(strtolower($ext)=="xml"){
					if($xml=="vacio"){
						$xml = "./adjuntos/" . $email_number . "-" . $filename;
					}else{
						//el mail contiene mas de un xml
						echo "Error +XML";
					}
					
				}else if(strtolower($ext)=="pdf"){
					if($pdf=="vacio"){
					    $pdf = "./adjuntos/" . $email_number . "-" . $filename;
					}else{
						//el mail contiene mas de un PDF
                        //$correo = new enviarMail("[email protected]");
						echo "Error +PDF";
					}
				}
				
				if($xml != "vacio" && $pdf != "vacio"){
                    //echo "Correo ".$from[0]->mailbox.'@'.$from[0]->host;
					$guardar = new readXML($xml,$pdf,$from[0]->mailbox.'@'.$from[0]->host);
				}*/







			}
        }
    
    }
    //echo "Aca ".$xmlArray[0];
    sort($xmlArray);
    sort($pdfArray);
    //print_r($pdfArray);
    //print_r($xmlArray);
    foreach ($xmlArray as $clave => $valor) {
        foreach ($pdfArray as $clave => $valorpdf) {
            if($valor==$valorpdf){
                //echo "Encontrado ".$valorpdf."<br>";
                $xml = "./adjuntos/". $valor.".xml";
                $pdf = "./adjuntos/". $valorpdf.".pdf";
                //echo "Correo ".$from[0]->mailbox.'@'.$from[0]->host;
                //echo "el xml ".$xml."<br>";
                $guardar = new readXML($xml,$pdf,$from[0]->mailbox.'@'.$from[0]->host);
                break;
            }
        }
    }
    unset($pdfArray);
    unset($xmlArray);
    if($count++ >= $max_emails) break;
}

}

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

echo “Done”;
//$resultado = readXMLRFC(“fact.xml”);

?>[/php]

I would do your testing in a real webpage instead of a CRON job. The problem is that you do not really
know if the CRON job is running or if it is stalled. You can log into your server, check the status of the CRON
and view it’s server logs and try to sort it out. But, it is much much easier to just create a webpage and
walk down how it works displaying it’s results. Then, if there is an error, you can have it displayed and just
refresh the page while testing… You have included two libraries. The first one, readXML obviously reads
XML and no idea what the other is. I could not locate it online… Does it pertain to this project?

As far as the code, I do not see anything odd immediately. All of the commands are normal. I do not have
an IMAP account at the moment, but, could create one for testing. I think first we need to know what error
you are getting from the code. How have you debugged it so far. Can it read the emails at all? Did you
look at the server logs yet? Since CRON jobs run on the server they do not echo to the screen unless you
test it by bringing up the job in browser. That does not always work, though. Depends on the server setup.

So, please give us further info on where it is breaking and we should be able to help…

Thanks, the issue was the url of the cron job. i miss a folder to make it work

Great! I will mark this one solved then. Thanks for letting us know…

Sponsor our Newsletter | Privacy Policy | Terms of Service