<?php
 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  *                    *
  *    Fichier  	:	mailer.php         *
  *    Créé le  	:	29 juin 2002        *
  *    Dernière modif  :	07 novembre 2002        *
  *    Email  	:  wascripts@phpcodeur.net      *
  *    © Copyright 2002 PHPcodeur          *
  *                      *
  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  *                   *
  *  This program is free software; you can redistribute it and/or  *
  *  modify it under the terms of the GNU General Public License as *
  *  published by the Free Software Foundation; either version 2 of *
  *  the License, or (at your option) any later version.      *
  *                    *
  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
     /*
  *  Classe d'envoi des emails.
  *  Fonctionne aussi chez online et nexen
  *  Gère l'attachement de pièces jointes et l'envoi d'emails au format html
  *
  */
     class Mailer {
    // chemin par défaut pour les modèles d'emails
  var $root = 'language/francais/email/';
  
  // vous devez définir la fonction mail qu'utilise votre hébergeur
  //
  //    // 1 pour la fonction mail() classique
  // 2 pour la fonction email() de online
  // 3 pour la fonction email() de nexen
  //
  var $hebergeur = 1;    
  // ou bien, vous pouvez utiliser un smtp en fournissant les données nécessaires ici
  //
  // $smtp_mode    // Mettez à true si vous voulez utiliser un serveur smtp
  //
  // Remplissez le tableau pour indiquer au script les données qui lui permettront de se    // connecter au serveur.
  //
  // host -> nom ou ip du serveur smtp (ex: smtp.wanadoo.fr)
  // port -> port utilisé (en général 25)
  // user -> login pour la connexion (seulement si nécessaire)
  // pass -> password pour la connexion (seulement si nécessaire)
  
  var $smtp_mode = false;
  
  var $smtp = array(
    'host' => '',      'port' => 25,      'user' => '',      'pass' => ''    	);
  //
  // Tableau des extensions et de leur Mime-Type
  // Rien ne vous interdit d'en rajouter si besoin est.
  //
  var $mime_type = array(
    'txt'  => 'text/plain',      'rtx'  => 'text/richtext',      'html' => 'text/html',      'htm'  => 'text/html',      'xml'  => 'text/xml',      'xls'  => 'text/xml',      'tsv'  => 'text/tab-separated-value',      'etx'  => 'text/x-setext',      
    'eml'  => 'message/rfc822',      'nws'  => 'message/rfc822',        'bmp'  => 'image/bmp',      'pcx'  => 'image/bmp',      'gif'  => 'image/gif',      'ief'  => 'image/ief',      'jpeg' => 'image/jpeg',      'jpg'  => 'image/jpeg',      'jpe'  => 'image/jpeg',      'png'  => 'image/png',      'tiff' => 'image/tiff',      'tif'  => 'image/tiff',      'cmu'  => 'image/x-cmu-raster',      'pnm'  => 'image/x-portable-anymap',      'pbm'  => 'image/x-portable-bitmap',      'pgm'  => 'image/x-portable-graymap',      'ppm'  => 'image/x-portable-pixmap',      'rgb'  => 'image/x-rgb',      'xbm'  => 'image/x-xbitmap',      'xpm'  => 'image/x-xpixmap',      'xwd'  => 'image/x-xwindowdump',        'dwg'  => 'application/acad',      'ccad' => 'application/clariscad',      'drw'  => 'application/drafting',      'dxf'  => 'application/dxf',      'xls'  => 'application/excel',      'hdf'  => 'application/hdf',      'unv'  => 'application/i-deas',      'igs'  => 'application/iges',      'iges' => 'application/iges',      'doc'  => 'application/msword',      'dot'  => 'application/msword',      'wrd'  => 'application/msword',      'oda'  => 'application/oda',      'pdf'  => 'application/pdf',      'ppt'  => 'application/powerpoint',      'ai'   => 'application/postscript',      'eps'  => 'application/postscript',      'ps'   => 'application/postscript',      'rtf'  => 'application/rtf',      'rm'   => 'application/vnd.rn-realmedia',      'dvi'  => 'application/x-dvi',    
    'gtar' => 'application/x-gtar',      'tgz'  => 'application/x-gtar',      'swf'  => 'application/x-shockwave-flash',      'tar'  => 'application/x-tar',      'gz'   => 'application/x-gzip-compressed',      'zip'  => 'application/x-zip-compressed',        'au'   => 'audio/basic',      'snd'  => 'audio/basic',      'aif'  => 'audio/x-aiff',      'aiff' => 'audio/x-aiff',      'aifc' => 'audio/x-aiff',    
    'wma'  => 'audio/x-ms-wma',        'mpeg' => 'video/mpeg',      'mpg'  => 'video/mpeg',      'mpe'  => 'video/mpeg',      'mov'  => 'video/quicktime',      'avi'  => 'video/msvideo',      'movie'=> 'video/x-sgi-movie',         //'unknow' => 'application/octet-stream',      'unknow' => 'application/x-unknown-content-type'    	);
  
  // Format de l'email
  // 1 pour format texte brut
  // 2 pour format html
  var $format = 1;    
  var $from_online = '';    var $reply_online = '';    var $from = array();
  var $to = array(
    'to'  => array(),      'cc'  => array(),      'bcc' => array()    	);    var $subject = '';
  var $message = '';
  var $altmessage = '';
  var $attachfile = array();
  var $boundary_attach = '';
  var $boundary_alternative = '';
  var $headers = array();
  
  // Jeu de caractère
  var $charset = "iso-8859-1";
  // Encodage de l'email
  // 7bit, 8bit, quoted-printable, base64, binary
  var $encoding = "8bit";    var $auto_encode = false;    
  var $server = 'localhost';
  var $smtp_bits = 8;
  var $mail_reponse = ''; // Variable contenant le message d'erreur en cas d'échec de l'envoi.
  
  var $debug = false;    
  var $statut = true;
  
  /*
   * Mailer : Mailer()
   *     * @param string $dir : Chemin vers les modèles d'email
   *     * @return void
   */
  function Mailer($dir = '')
  {
  	if( $dir != '' )
  	{
    $this->set_root($dir);
  	}
  }
  
  /*
   * Mailer : set_root()
   *     * @param string $dir : Nom de dossier
   *     * @return boolean
   */
  function set_root($dir)
  {
  	if( !is_dir($dir) )
  	{
    $this->error("set_root()","Le chemin \"<b>$dir</b>\" est incorrect." );
    return false;
  	}
    	$this->root = $dir;
  	return true;
  }
  
  /*
   * Mailer : set_file()
   *     * @param string $path  : Chemin vers le fichier
   *     * @return boolean
   */
  function set_file($path)
  {
  	$file = basename($path);
      	if( !file_exists($path) )
  	{
    $this->error("set_file()","Le fichier \"<b>$file</b>\" est introuvable" );
    return false;
  	}
  	else if( !is_readable($path) )
  	{
    $this->error("set_file()","Le fichier \"<b>$file</b>\" n'est pas accessible en lecture" );
    return false;
  	}
      	return true;
  }
  
  /*
   * Mailer : set_smtp()
   *     * @param string $host  : Nom du serveur SMTP
   * @param integer $port : Port de connexion ( 25 dans la grande majorité des cas )
   * @param string $user  : Login d'authentification ( si AUTH est supporté par le serveur )
   * @param string $pass  : Password d'authentification
   *     * @return void
   */
  function set_smtp($host, $port = '', $user = '', $pass = '' )
  {
  	$this->smtp_mode = true;
  	$this->smtp['host'] = $host;
  	$this->smtp['port'] = ( $port != '' ) ? $port : $this->smtp['port'];
  	$this->smtp['user'] = ( $user != '' ) ? $user : $this->smtp['user'];
  	$this->smtp['pass'] = ( $pass != '' ) ? $pass : $this->smtp['pass'];
  }
  
  /*
   * Mailer : loadfile()
   *     * @param string $path  : Chemin vers le fichier
   * @param boolean $binary : on spécifie si on charge un fichier binaire     *     * @return string
   */
  function loadfile($path, $binary = false)
  {
  	$file = basename($path);      	$mode = ( $binary ) ? "rb" : "r";        	$fp = @fopen($path, $mode);
  	if( !$fp )
  	{
    $this->error('loadfile()', "Lecture du fichier \"<b>$file</b>\" impossible" );
    return false;
  	}
    	$content = fread($fp, filesize($path));
  	fclose($fp);
    	return $content;
  }
  
  /*
   * Mailer : set_format()
   *     * @param string ou integer $format : Format de l'email
   *     * @return void
   */
  function set_format($format)
  {
  	$format = strtolower($format);
      	switch($format)
  	{
    case "html":
    case "htm":
    case 2:
    	$this->format = 2;
    	break;
    
    case "texte":
    case "txt":
    case "text":
    case 1:
    default:
    	$this->format = 1;
    	break;
  	}
  }
  
  /*
   * Mailer : set_from()
   *     * @param string $email_from  : Email de l'expéditeur
   * @param string $name_from  : Personnalisation du nom de l'expéditeur
   *     * @return void
   */
  function set_from($email_from, $name_from = '')
  {
  	$this->from['email'] = trim($email_from);
  	$this->from['name'] = trim($name_from);
      	if( $this->hebergeur == 2 )
  	{
    $pos = strpos($this->from['email'], "@" );    
    $this->from_online = substr($this->from['email'], 0, $pos);      $this->reply_online = $this->from_online;    	}
  	else
  	{
    $this->headers['From'] = ( $this->from['name'] != '' ) ? "\"" . $this->from['name'] . "\" " : "";
    $this->headers['From'] .= "<" . $this->from['email'] . ">";
    
    $this->headers['Reply-To'] = $this->from['email'];        $this->headers['Return-Path'] = $this->from['email'];
    $this->headers['X-Sender'] = "<" . $this->from['email'] . ">";
    
    
    
  	}
  }
  
  /*
   * Mailer : set_to()
   *     * @param array $dest  : Tableau contenant la liste des destinataires
   * @param string $type  : Type d'envoi aux destinataires(cc ou bcc)
   *     * @return void
   */
  function set_to($dest, $type = '')
  {
  	if( !is_array($dest) )
  	{
    $this->error('set_to()', "Argument incorrect, set_to() doit recevoir un tableau." );
  	}
      	$type = ( $type != '' ) ? strtolower($type) : '';
      	if( $type != 'cc' && $type != 'bcc' )
  	{
    $type = 'to';
  	}
      	reset($dest);
  	while( list($name, $email) = each($dest) )
  	{
    $name = ( !ereg("^[0-9]+$", $name) ) ? $name : '';
    
    $this->to[$type][] = array(
    	'email' => trim($email),      	'name'  => trim($name)      );
  	}
  }
  
  /*
   * Mailer : set_subject()
   *     * @param string $subject : Le sujet de l'email
   *     * @return void
   */
  function set_subject($subject)
  {
  	$this->subject = trim($subject);
  }
  
  /*
   * Mailer : set_message()
   *     * @param string $var  	: contient soit le message, soit le nom du modèle d'email à lire
   * @param array $vararray  : Tableau contenant les variables à remplacer dans le modèle
   *     * @return void
   */
  function set_message($var, $vararray = '')
  {
  	if( is_array($vararray) )
  	{
    $this->set_root($this->root);
    $path = ( ( substr($this->root, -1, 1) != '/' ) ? $this->root . '/' : $this->root ) . $var;
    $message = $this->loadfile($path);
    
    reset($vararray);
    while( list($key, $val) = each($vararray) )
    {
    	$key = '%'.$key.'%';
    	$message = str_replace($key, $val, $message);
    }
    
    $this->message = trim($message);      $this->message = str_replace("\r\n", "\n", $this->message);    	}
  	else
  	{
    $this->message = trim($var);
  	}
      	if( @extension_loaded('imap') && @function_exists('imap_8bit') && $this->auto_encode )
  	{
    $this->encoding = 'quoted-printable';    
    $this->message = imap_8bit($this->message);    	}
  }
  
  /*
   * Mailer : set_Altmessage()
   *     * @param string $var  	: contient soit le message, soit le nom du modèle d'email à lire
   * @param array $vararray  : Tableau contenant les variables à remplacer dans le modèle
   *     * @return void
   */
  function set_Altmessage($var, $vararray = '')
  {
  	if( is_array($vararray) )
  	{
    $this->set_root($this->root);
    $path = ( ( substr($this->root, -1, 1) != '/' ) ? $this->root . '/' : $this->root ) . $var;
    $message = $this->loadfile($path);
    
    reset($vararray);
    while( list($key, $val) = each($vararray) )
    {
    	$key = '%'.$key.'%';
    	$message = str_replace($key, $val, $message);
    }
    
    $this->altmessage = trim($message);      $this->altmessage = str_replace("\r\n", "\n", $this->altmessage);    	}
  	else
  	{
    $this->altmessage = trim($var);
  	}
      	if( @extension_loaded('imap') && @function_exists('imap_8bit') && $this->auto_encode )
  	{
    $this->encoding = 'quoted-printable';      $this->altmessage = imap_8bit($this->altmessage);    	}
  }
  
  /*
   * Mailer : attachment()
   *     * @param $path  	: Chemin vers le fichier
   * @param $filename  : Nom du fichier
   * @param $disposition	: Disposition
   * @param $mime_type	: Mime-type
   *  
   * @return void
   */
  function attachment($path, $filename = "", $disposition = "", $mime_type = "" )
  {
  	$result = $this->set_file($path);
      	if( $result )
  	{
    $this->attachfile[] = array(
    	'path' => $path,      	'name' => ( $filename != "" ) ? trim($filename) : basename($path),      	'disposition' => ( $disposition == "inline" ) ? "inline" : "attachment",      	'mimetype' => $mime_type      );
  	}
  }
  
  /*
   * Mailer : set_notify()
   *     * @return void
   */
  function set_notify()
  {
  	$this->headers['Disposition-Notification-To'] = "<" . $this->from['email'] . ">";
  }
  
  /*
   * Mailer : organization()
   *     * @return void
   */
  function organization($soc)
  {
  	$this->headers['Organization'] = $soc;
  }
  
  /*
   * Mailer : set_priority()
   *     * @param string ou integer $level : Niveau de priorité de l'email
   *     * @return void
   */
  function set_priority($level)
  {
  	$level = strtolower($level);
      	switch($level)
  	{
    case 1:
    case "highest":
    	$this->headers['X-Priority'] = "1";
    	$this->headers['X-MSMail-Priority'] = "Highest";
    	break;
    
    case 2:
    case "hight":
    	$this->headers['X-Priority'] = "2";
    	$this->headers['X-MSMail-Priority'] = "High";
    	break;
    
    case 4:
    case "low":
    	$this->headers['X-Priority'] = "4";
    	$this->headers['X-MSMail-Priority'] = "Low";
    	break;
    
    case 5:
    case "lowest":
    	$this->headers['X-Priority'] = "5";
    	$this->headers['X-MSMail-Priority'] = "Lowest";
    	break;
    
    case 3:
    case "normal":
    default:
    	$this->headers['X-Priority'] = "3";
    	$this->headers['X-MSMail-Priority'] = "Normal";
    	break;
  	}
  }
  
  /*
   * Mailer : set_header()
   *     * @param string $header : Nom de l'entête à modifier
   * @param string $str  : Contenu de l'entête
   *     * @return void
   */
  function set_header($header, $str)
  {
  	if( $header != '' && $str != '' )
  	{
    if( strpos($header, "-" ) )
    {
    	$elt = explode("-", $header);
          	while( list($key, $value) = each($elt) )
    	{
      $item[] = ucfirst($value);
    	}
          	$header = implode("-", $item);
    }
    else
    {
    	$header = ucfirst($header);
    }
    
    $this->headers[$header] = $str;
  	}
  }
  
  /*
   * Mailer : send()
   *     * @return boolean
   */
  function send()
  {
  	if( count($this->to['to']) == 0 )
  	{
    $this->to['to'][] = array(
    	'email' => $this->from['email'],      	'name' => $this->from['name']      );
  	}
      	if( count($this->to['to']) == 0 )
  	{
    $this->error('send()', "Aucun destinataire principal n'a été défini" );
    return false;
  	}
      	$to_list = '';
  	$total_to = count($this->to['to']);
  	for( $i = 0; $i < $total_to; $i++ )
  	{
    $to_list .= ( $i > 0 ) ? ", " : "";
    $to_list .= ( $this->to['to'][$i]['name'] != '' ) ? "\"" . $this->to['to'][$i]['name'] . "\" " : "";
    $to_list .= "<" . $this->to['to'][$i]['email'] . ">";
  	}
      	$this->build_headers($to_list);
  	$this->build_message();
      	if( !$this->statut )
  	{
    return false;
  	}  
  	else if( $this->smtp_mode )
  	{
    $result = $this->mailsmtp($this->to, $this->subject, $this->message, $this->headers);
  	}
  	else if( $this->hebergeur == 1 )
  	{
    $result = @mail($to_list, $this->subject, $this->message, $this->headers);
  	}
  	else if( $this->hebergeur == 2 )
  	{
    $result = @email($this->from_online, $to_list, $this->subject, $this->message, $this->reply_online, $this->headers);    	}
  	else if( $this->hebergeur == 3 )
  	{
    include_once("mail.inc" );
    $result = @email($to_list, $this->subject, $this->message, $this->headers);
  	}
  	else
  	{
    $this->error('send()', "Aucune fonction d'envoi n'est définie." );
    $result = false;
  	}
  	echo "ici : $result";
  return $result;
  }
  
  /*
   * Mailer : build_headers()
   *     * @param string $to_list	: Liste des adresses des destinataires, de la forme : <adresse@domain.com>, ...
   *     * @return void
   */
  function build_headers($to_list)
  {
  	global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
      	if( $this->smtp_mode )
  	{
    $this->headers['Subject'] = $this->subject;
    $this->headers['To'] = $to_list;
  	}
      	if( count($this->to['cc']) > 0 && !$this->smtp_mode )
  	{
    $cc_list = '';
    $total_cc = count($this->to['cc']);
    for( $i = 0; $i < $total_cc; $i++ )
    {
    	$cc_list .= ( $i > 0 ) ? ", " : "";
    	$cc_list .= ( $this->to['cc'][$i]['name'] != '' ) ? "\"" . $this->to['cc'][$i]['name'] . "\" " : "";
    	$cc_list .= "<" . $this->to['cc'][$i]['email'] . ">";
    }
      $this->headers['Cc'] = $cc_list;
  	}
      	if( count($this->to['bcc']) > 0 && !$this->smtp_mode )
  	{
    $bcc_list = '';
    $total_bcc = count($this->to['bcc']);
    for( $i = 0; $i < $total_bcc; $i++ )
    {
    	$bcc_list .= ( $i > 0 ) ? ", " : "";
    	$bcc_list .= ( $this->to['bcc'][$i]['name'] != '' ) ? "\"" . $this->to['bcc'][$i]['name'] . "\" " : "";
    	$bcc_list .= "<" . $this->to['bcc'][$i]['email'] . ">";
    }
        $this->headers['Bcc'] = $bcc_list;
  	}
      	$this->headers['Date'] = date('D, d M Y H:i:s O', time());
  	$this->headers['X-Mailer'] = "WAmailer/1.4 PHP/" . phpversion();
      	if( !empty($HTTP_SERVER_VARS['SERVER_NAME']) || !empty($HTTP_ENV_VARS['SERVER_NAME']) )
  	{
    $server = ( !empty($HTTP_SERVER_VARS['SERVER_NAME']) ) ? $HTTP_SERVER_VARS['SERVER_NAME'] : $HTTP_ENV_VARS['SERVER_NAME'];
  	}
  	else if( !empty($HTTP_SERVER_VARS['HTTP_HOST']) || !empty($HTTP_ENV_VARS['HTTP_HOST']) )
  	{
    $server = ( !empty($HTTP_SERVER_VARS['HTTP_HOST']) ) ? $HTTP_SERVER_VARS['HTTP_HOST'] : $HTTP_ENV_VARS['HTTP_HOST'];
  	}
  	else
  	{
    $server = '';
  	}
      	$this->server = ( $server != '' ) ? $server : $this->server;
    	$sender_ip = ( !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) ) ? $HTTP_SERVER_VARS['REMOTE_ADDR'] : ( ( !empty($HTTP_ENV_VARS['REMOTE_ADDR']) ) ? $HTTP_ENV_VARS['REMOTE_ADDR'] : '' );
    	if( $sender_ip && $server )
  	{
    $this->headers['X-AntiAbuse'] = "Sender IP - $sender_ip Server Name - <$server>";
  	}
      	$this->boundary_attach = "-----=_attach_" . md5( uniqid ( rand() ) );
  	$this->boundary_alternative = "-----=_alt_" . md5( uniqid ( rand() ) );
      	$total_attach = count($this->attachfile);
  	if( $total_attach > 0 )
  	{
    $this->headers['MIME-Version'] = "1.0";
    $this->headers['Content-Type'] = "multipart/mixed; boundary=\"" . $this->boundary_attach . "\"";
  	}
  	else if( $this->message != '' && $this->altmessage != '' && $this->format == 2 )
  	{
    $this->headers['MIME-Version'] = "1.0";
    $this->headers['Content-Type'] = "multipart/alternative; boundary=\"" . $this->boundary_alternative . "\"";
  	}
  	else
  	{
    $this->headers['Content-Type'] = ( $this->format == 2 ) ? "text/html; charset=\"" . $this->charset . "\"" : "text/plain; charset=" . $this->charset;
    $this->headers['Content-Transfer-Encoding'] = $this->encoding;
  	}
      	$headers = '';
  	$i = 0;
  	$total_headers = count($this->headers);
  	while( list($title_header, $content_header) = each($this->headers) )
  	{
    $headers .= $title_header . ": " . $content_header;
    $headers .= ( ($i + 1) < $total_headers ) ? "\n" : "";
    $i++;
  	}
      	$this->headers = $headers;
  }
  
  /*
   * Mailer : build_message()
   *     * @return void
   */
  function build_message()
  {
  	$total_attach = count($this->attachfile);    	$message = '';        	if( $this->message != '' && $this->altmessage != '' && $this->format == 2 )
  	{
    $message = "--" . $this->boundary_alternative . "\n";
    $message .= "Content-Type: text/plain; charset=" . $this->charset . "\n";
    $message .= "Content-Transfer-Encoding: " . $this->encoding . "\n\n";
    $message .= $this->altmessage;
    $message .= "\n\n";
    $message .= "--" . $this->boundary_alternative . "\n";
    $message .= "Content-Type: text/html; charset=\"" . $this->charset . "\"\n";
    $message .= "Content-Transfer-Encoding: " . $this->encoding . "\n\n";
    $message .= $this->message;
    $message .= "\n\n";
    $message .= "--" . $this->boundary_alternative . "--\n";        
    $this->message = $message;
  	}
      	if( $total_attach > 0 )
  	{
    $message = "--" . $this->boundary_attach . "\n";
    
    if( $this->message != '' && $this->altmessage != '' && $this->format == 2 )
    {
    	$message .= "Content-Type: multipart/alternative; boundary=\"" . $this->boundary_alternative . "\"\n\n";
    }
    else if( $this->format == 2 )
    {
    	$message .= "Content-Type: text/html; charset=\"" . $this->charset . "\"\n";
    	$message .= "Content-Transfer-Encoding: " . $this->encoding . "\n\n";
    }
    else
    {
    	$message .= "Content-Type: text/plain; charset=" . $this->charset . "\n";
    	$message .= "Content-Transfer-Encoding: " . $this->encoding . "\n\n";
    }
    
    $message .= $this->message;
    $message .= "\n\n";
    
    for( $i = 0; $i < $total_attach; $i++ )
    {
    	$content = chunk_split(base64_encode($this->loadfile($this->attachfile[$i]['path'], true)));
          	$mime_type = '';
    	$extension = '';
          	if( $this->attachfile[$i]['mimetype'] != '' )
    	{
      $mime_type = $this->attachfile[$i]['mimetype'];
    	}
    	else
    	{
      if( strpos($this->attachfile[$i]['name'], "." ) )
      {
      	$elt = explode(".", $this->attachfile[$i]['name']);
      	$num = count($elt);
      
      	$extension = strtolower($elt[$num - 1]);
      	$mime_type = ( !empty($this->mime_type[$extension]) ) ? $this->mime_type[$extension] : '';
      }
      
      if( $mime_type == '' )
      {
      	$mime_type = $this->mime_type["unknow"];
      }
    	}
          	$message .= "--" . $this->boundary_attach . "\n";    
    	$message .= "Content-Type: $mime_type; name=\"" . $this->attachfile[$i]['name'] . "\"\n";
    	$message .= "Content-Transfer-Encoding: base64\n";
    	$message .= "Content-Disposition: " . $this->attachfile[$i]['disposition'] . "; filename=\"" . $this->attachfile[$i]['name'] . "\"\n\n";    
    	$message .= $content;
    	$message .= "\n\n";
      }
    
    $message .= "--" . $this->boundary_attach . "--\n";
    
    $this->message = $message;
  	}
      	if( ($this->message != '' && $this->altmessage != '' && $this->format == 2 ) || $total_attach > 0 )
  	{
    $this->message = "This is a multi-part message in MIME format.\n\n" . $this->message;
  	}
  }
  
  /*
   * Mailer : mailsmtp()
   *
   * Description : Envoi d'emails via connexion au serveur smtp défini.
   *     * @param array $to  	: tableau contenant la liste des adresses directe (to), la liste des     *          copie (cc) et la liste des copies cachées (bcc)
   * @param string $subject  : Le sujet de l'email
   * @param string $message  : Le message construit (fichier attaché ou pas, etc...)
   * @param array $headers  : Le tableau contenant les entetes
   *     * @return boolean
   *
   * Les sources qui m'ont bien aidées :     *     * @link : http://www.rfc-editor.org/
   * @link : http://strasbourg.ort.asso.fr/examen2000/np.html#SMTP
   * @link : http://www.commentcamarche.net/internet/smtp.php3
   * @link : http://abcdrfc.free.fr/
   * @link : http://www.interpc.fr/mapage/billaud/telmail.htm
   *
   * Toutes les commandes de connexion et de dialogue avec le serveur sont     * détaillées dans la RFC 821.
   *     * Les commandes d'authentification au serveur sont détaillées dans     * la RFC 2554 ( note: Impossible de trouver cette fichu RFC 2554 en français ou     * de trouver des infos satisfaisantes sur la commande AUTH ).
   *     * @link : http://www.rfc-editor.org/rfc/rfc2554.txt
   *     */    function mailsmtp($to, $subject, $message, $headers)
  {
  	$authentification = ( !empty($this->smtp['user']) && !empty($this->smtp['pass']) ) ? true : false;
      	// Ouverture de la connexion au serveur SMTP
  	$socket = @fsockopen($this->smtp['host'], $this->smtp['port'], $errno, $errstr);
  	if( !$socket )
  	{
    $this->error('mailsmtp()', "Echec lors de la connexion au serveur smtp : $errno $errstr" );
    return false;
  	}
      	//    	// Code success : 220
  	// Code failure : 421
  	//  
  	$result = $this->parse_reponse($socket, "220", __LINE__);
  	if( !$result ) return false;
      	//
  	// Comme on est poli, on dit bonjour.
  	// Selon que le serveur supporte les messages 8bits ou pas, EHLO ou HELO
  	// mais ce n'est apparamment pas primordial.
  	//
  	// Code success	: 250
         // Code error	: 500, 501, 504, 421
  	//
  	$welcome = ( $this->smtp_bits == '8' ) ? "EHLO " . $this->server : "HELO " . $this->server;
      	fputs($socket, $welcome . "\r\n" );    	$result = $this->parse_reponse($socket, "250", __LINE__);
  	if( !$result ) return false;
      	if( $authentification )
  	{
    fputs($socket, "AUTH LOGIN\r\n" );
    $result = $this->parse_reponse($socket, "334", __LINE__);
    if( !$result ) return false;
    
    fputs($socket, base64_encode($this->smtp['user']) . "\r\n" );
    $result = $this->parse_reponse($socket, "334", __LINE__);
    if( !$result ) return false;
    
    fputs($socket, base64_encode($this->smtp['pass']) . "\r\n" );
    $result = $this->parse_reponse($socket, "235", __LINE__);
    if( !$result ) return false;
  	}
      	//
  	// On spécifie l'adresse de l'expéditeur
  	//
  	// Code success	: 250
         // Code failure	: 552,451,452
         // Code error	: 500,501,421
  	//
  	fputs($socket, "MAIL FROM: <" . $this->from['email'] . ">\r\n" );
  	$result = $this->parse_reponse($socket, "250", __LINE__);
  	if( !$result ) return false;
      	//
  	// On spécifie les destinatires au serveur smtp
  	//
  	// Code success	: 250,251
         // Code failure	: 550,551,552,553,450,451,452
         // Code error	: 500,501,503,421
  	//
      	reset($to['to']);
  	while( list(, $email_to) = each($to['to']) )
  	{
    fputs($socket, "RCPT TO: <" . $email_to['email'] . ">\r\n" );      $result = $this->parse_reponse($socket, "250", __LINE__);
    if( !$result ) return false;
  	}
      	reset($to['cc']);
  	while( list(, $email_to) = each($to['cc']) )
  	{
    fputs($socket, "RCPT TO: <" . $email_to['email'] . ">\r\n" );      $result = $this->parse_reponse($socket, "250", __LINE__);
    if( !$result ) return false;
  	}
      	reset($to['bcc']);
  	while( list(, $email_to) = each($to['bcc']) )
  	{
    fputs($socket, "RCPT TO: <" . $email_to['email'] . ">\r\n" );      $result = $this->parse_reponse($socket, "250", __LINE__);
    if( !$result ) return false;
  	}
      	//
  	// On indique au serveur que l'on va lui livrer les données
  	//
  	// Code success	: 354
  	//
  	fputs($socket, "DATA\r\n" );
  	$result = $this->parse_reponse($socket, "354", __LINE__);
  	if( !$result ) return false;
      	// On envoie les entêtes
  	fputs($socket, "$headers\r\n\r\n" );
    	// Et maintenant le message
  	fputs($socket, "$message\r\n" );
    	//
  	// On indique la fin de l'envoi de données au serveur
  	//
  	// Code success	: 250
         // Code failure	: 552,554,451,452
         // Code error	: 500,501,503,421
  	//
  	fputs($socket, ".\r\n" );
  	$result = $this->parse_reponse($socket, "250", __LINE__);
  	if( !$result ) return false;
    	// Comme on est poli, on dit aurevoir au serveur avec la commande adéquat QUIT
  	fputs($socket, "QUIT\r\n" );
  	fclose($socket);
      	return true;
  }
    /*
   * Mailer : parse_reponse()
   *     * @param resource $socket  : Identifiant de connexion avec le serveur SMTP
   * @param integer $code  : Le code qui doit être obtenu pour continuer
   * @param integer $line  : La ligne où s'est produite l'erreur (pour mieux s'y retrouver)
   *     * @return boolean
   */
  function parse_reponse($socket, $code, $line)
  {
  	$reponse = '';    	while( substr($reponse, 3, 1) != ' ' )
  	{
    $reponse = fgets($socket, 500);
  	}
      	if( $code == "220" )
  	{
    $this->smtp_bits = ( ereg("ESMTP", $reponse) ) ? 8 : 7;
  	}
      
  	if( !( substr($reponse, 0, 3) == $code) )
  	{
    $this->error('send()', "Un problème est survenu durant l'envoi via smtp :<br /><br /> " . nl2br( htmlentities($reponse) ) . " <br />Ligne : $line" );
    return false;
  	}
      	return true;
  }
  
  /*
   * Mailer : init()
   *     * @return void
   */
  function init()
  {
  	$this->from_online = '';    	$this->reply_online = '';    	$this->from = array();
  	$this->to = array(
    'to'  => array(),      'cc'  => array(),      'bcc' => array()    	);    	$this->subject = '';
  	$this->message = '';
  	$this->altmessage = '';
  	$this->attachfile = array();
  	$this->boundary_attach = '';
  	$this->boundary_alternative = '';
  	$this->headers = array();
      	$this->mail_reponse = '';
  	$this->statut = true;    }
    /*
   * Mailer : error()
   *     * @param string $fct  : La dernière fonction où s'est produite l'erreur
   * @param string $error : Le message d'erreur à afficher si mode debug
   *     * @return void
   */
  function error( $fct, $error)
  {
  	$this->mail_reponse = sprintf("<br /><br />%s <b>Erreur</b> : %s", $fct, $error);        	$this->statut = false;
      	if( $this->debug )
  	{
    echo $this->mail_reponse;
    exit;
  	}
  }
  
 }// fin de classe
 ?>
   |