Asterisk Mail2Fax using FFA in poor man style !

FUNNY_TOILETS_LONMED_2549_03The serious name is email to fax gateway, but we prefer to call it “email2fax in poor man style”.
Problem
We have an asterisk pbx with Fax for Asterisk module from Digium installed correctly (or SpanDSP), and we want to implement in a very simple and fast way an email2fax procedure.
We can use the very simple script below, that we can run automatically every 10 min using cron.

Att.: In this script we are using an IMAP email account and the PHPmailer library.
We have to send an email to IMAP email account with only 1 pdf attach, and in the subject only the fax number: a Fax Delivery Receipt via email will be send to the sender.

Att.: In this post I used FFA: but you can use instead SpanDSP and should be the same (I’m sure…), althought I’ve not tested !

<!--?php require_once('/var/spool/mail2fax/PHPMailer-master/class.phpmailer.php'); function str_ends_with($haystack, $needle) { return substr_compare($haystack, $needle, -strlen($needle))=== 0; } function loggo($stringa) { file_put_contents('/var/log/mail2fax.log',date('Y-m-d H:i:s').": ".$stringa."\r\n",FILE_APPEND); } //Cancello tutti i file in tmp function cancellotmp() { $files = glob('/var/spool/mail2fax/tmp/*'); // get all file names foreach($files as $file){ if(is_file($file)) unlink($file); } } function inviomailesito() { $filesrxmail = glob('/var/spool/mail2fax/wip/rxmail.txt'); $filedatifax = glob('/var/spool/mail2fax/wip/datifax.txt'); if (count($filesrxmail)==1 & count($filedatifax)==1){ $testomail=file_get_contents ("/var/spool/mail2fax/wip/rxmail.txt"); $lineedatifax = file("/var/spool/mail2fax/wip/datifax.txt"); $subjmail="Ricevuta trasmissione fax a ".$lineedatifax[0]."\n"; $email = new PHPMailer(); $email->From = '<From email for Fax Delivery Receipt>';
$email->FromName = 'Fax Delivery Receipt';
$email->Subject = $subjmail;
$email->Body = $testomail;
$email->AddAddress( $lineedatifax[1] );
$filesattach = glob('/var/spool/mail2fax/wip/*');

foreach($filesattach as $file){

if(is_file($file))
if ((substr($file, -strlen("tif")) != "tif") & (basename($file)!="datifax.txt"))
$email->AddAttachment($file, basename($file) );
}

$email->Send();
loggo("Inviata Mail: ".$testomail);
}

if (count($filedatifax)==1){

$lineedatifax = file("/var/spool/mail2fax/wip/datifax.txt");
$testomail= "Fax occupato o numero errato";
$subjmail="Ricevuta trasmissione fax a ".$lineedatifax[0]."\n";
$email = new PHPMailer();
$email->From = '<From email for Fax Delivery Receipt>';
$email->FromName = 'Fax Delivery Receipt-Error';
$email->Subject = $subjmail;
$email->Body = $testomail;
$email->AddAddress( $lineedatifax[1] );
$filesattach = glob('/var/spool/mail2fax/wip/*');
foreach($filesattach as $file){
if(is_file($file))
if ((substr($file, -strlen("tif")) != "tif") & (basename($file)!="datifax.txt"))
$email->AddAttachment($file, basename($file) );
}

$email->Send();
loggo("Inviata Mail: ".$testomail);
}

$filescanc = glob('/var/spool/mail2fax/wip/*');
foreach($filescanc as $file){
if(is_file($file))
unlink($file);
}
}

function invioavvisomailerrata($mailfrom)
{
$email = new PHPMailer();
$email->From = '<From email for Fax Delivery Receipt>';
$email->FromName = 'Fax Delivery Receipt-Wrong or busy Nr';
$email->Subject = "Mail per sistema mail2fax errata";
$email->Body = "Mail per sistema mail2fax errata";
$email->AddAddress( $mailfrom );
$email->Send();
}

set_time_limit(3000);
loggo("Alive---");

$hostname = '{<inboux IMAP address>}INBOX';
$username = '<login account>';
$password = '

<password account>';

inviomailesito();

$inbox = imap_open($hostname,$username,$password) or loggo("Errore connessione a casella Imap ".imap_last_error());

$mailconsoggettonumerico=false;
$mailattachpdf='';

$emails = imap_search($inbox,'UNSEEN');
if($emails) {
cancellotmp();
loggo("-Ricezione Mail");
$overview = imap_fetch_overview($inbox,$emails[0],0);
loggo("--Soggetto Mail: ".$overview[0]->subject);
if(is_numeric($overview[0]->subject))
{
$mailconsoggettonumerico=true;
}

$soggetto=$overview[0]->subject;
$headermail = imap_headerinfo($inbox, $emails[0]);
$mailfrom = $headermail->from[0]->mailbox . "@" . $headermail->from[0]->host;

$structure = imap_fetchstructure($inbox, $emails[0]);

if(!$mailconsoggettonumerico) {
$message = imap_fetchbody($inbox,$emails[0],1);
imap_close($inbox,CL_EXPUNGE);
exit;
}

$attachments = array();
if(isset($structure->parts) && count($structure->parts))
{
$parti=count($structure->parts);
for($i = 0; $i < count($structure->parts); $i++)
{
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, $emails[0], $i+1);

if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}

/* iterate through each attachment and save it */
loggo("-->Num di attach:".count($attachments)."\n");

$numattach=0;
//Check: must exist only 1 pdf file
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];

if(empty($filename)) $filename = time() . ".dat";

if (str_ends_with($filename,"pdf"))
{
$numattach= $numattach+1;
}

}
}

if ($numattach!=1)
{
imap_close($inbox,CL_EXPUNGE);
loggo("-->More than 1 pdf in attach - go out\n");
invioavvisomailerrata($mailfrom);
exit;
}

$nomefile=$emails[0] . ".pdf";

foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];

if(empty($filename)) $filename = time() . ".dat";

print_r("nome file".$filename."\n");
if (str_ends_with($filename,"pdf"))
{
$mailattachpdf=$filename;
print_r("E' PDF !!!");
}

$fp = fopen("/var/spool/mail2fax/tmp/" . $nomefile, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}

//convert from pdf to tiff
system("gs -q -dNOPAUSE -dBATCH -sDEVICE=tiffg4 -sOutputFile=/var/spool/mail2fax/tmp/".$nomefile.".tif /var/spool/mail2fax/tmp/".$nomefile);

//File Call
$callfile = "/var/spool/mail2fax/tmp/callfax.call";
$handle = fopen($callfile, 'w');
fwrite($handle,"channel: SIP/1111/".$overview[0]->subject."\n");
fwrite($handle,"Context: SendFax\n");
fwrite($handle,"Extension: send\n");
fwrite($handle,"Priority: 1\n");
fwrite($handle,"Set: FAXFILE=/var/spool/mail2fax/wip/" . $nomefile.".tif\n");
fwrite($handle,"Set: FaxID=".$emails[0]."\n");
fclose($handle);

//Ora preparo il file con i dati
$datifax = "/var/spool/mail2fax/tmp/datifax.txt";
$handle = fopen($datifax, 'w');
fwrite($handle,$overview[0]->subject."\n");
fwrite($handle,$mailfrom."\n");
fclose($handle);

system("mv /var/spool/mail2fax/tmp/* /var/spool/mail2fax/wip/");
system("mv /var/spool/mail2fax/wip/callfax.call /var/spool/asterisk/outgoing");

}else {
loggo("---Mail w/ Attach");
invioavvisomailerrata($mailfrom);

}

}

imap_close($inbox,CL_EXPUNGE);
?>

Linkografia
PhpMailer
Downloading Gmail attachments in PHP
Digium Fax for Asterisk