<?php
// Pour les 2 fonctions, le sujet n'est pas encodé, evitez d'utiliser les accents


// Envoi d'email
function envoi_mail($from, $to, $subject, $message)
{
    if ($_SESSION['choix_du_mail'] == 'UTILISER_MAIL_PHP') 
        envoi_mail_php($from, $to, $subject, $message);
    if ($_SESSION['choix_du_mail'] == 'UTILISER_SMTP') 
        if (!envoi_smtp($from, $to, $subject, $message)) echo ERREUR_ENVOI_SMTP;
}

//Envoi d'email en utilisant la fonction PHP
function envoi_mail_php($from, $to, $subject, $message)
{
    $headers = 'From: '.$from."\r\n";   
    $headers .= "MIME-Version: 1.0\r\n"."Content-type: text/plain; charset=utf-8\r\n";
    if (!mail($to,$subject,$message,$headers)) 
        echo ERREUR_ENVOI_MAIL_PHP;
}

//Envoi d'email en utilisant un serveur SMTP
function envoi_smtp($from, $to, $subject, $message)
{
    $dest = explode(", ", $to);
    $host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
    $serveurSMTP = $_SESSION['nom_du_serveur_smtp'];
    $headers = "MIME-Version: 1.0\r\n"."Content-type: text/plain; charset=utf-8\r\n";
       
    if ($from!=null && $to!=null && $subject!=null && $message!=null)
    { 
        $connection = fsockopen($serveurSMTP,25, $errno, $errstr, 6);
        if (!$connection)  
        {
            return false;
        } 
        else 
        {
            $res1=fgets($connection, 1024);
            if(substr($res1, 0, 3) != "220") return false;
        
            fputs($connection, "HELO ". $host."\r\n");
            $res2=fgets($connection, 1024);
            if(substr($res2, 0, 3) != "250") return false;
                 
            fputs($connection, "MAIL FROM: $from\r\n");
            $res3=fgets($connection, 1024);
            if(substr($res3, 0, 3) != "250") return false;
        
            for ($i=0; $i<count($dest); $i++) {
                fputs($connection, "RCPT TO: $dest[$i]\r\n");
                $res4=fgets($connection, 1024);
                if(substr($res4, 0, 3) != "250") return false;
            }
        
            fputs($connection, "DATA\r\n");
            $res5=fgets($connection, 1024);
            if(substr($res5, 0, 3) != "354") return false;
        
            fputs($connection, "TO:$to\nFrom:$from\nSubject:$subject\n$headers\n\n$message\n.\r\n");
            $res6=fgets($connection, 1024);
            if(substr($res6, 0, 3) != "250") return false;
        
            fputs($connection, "QUIT\r\n");
            $res7=fgets($connection, 1024);
            if(substr($res7, 0, 3) != "221") return false;
 
            fclose ($connection);
        }
        
        if (substr($res1, 0, 3) == "220" && substr($res2, 0, 3) == "250" && substr($res3,0, 3) == "250" && substr($res4, 0, 3) == "250" && substr($res5, 0, 3) == "354" && substr($res6, 0, 3) == "250" && substr($res7, 0, 3) == "221") 
            return true;
    }   
    
    else 
        { return false;}
}

?>
