diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php
index 8bb4b69ffe04ef131f454a423cab4e0aed8a9063..6749ff56f2a005e928368f6c3b2f1962ddc02d2b 100644
--- a/htdocs/admin/mails.php
+++ b/htdocs/admin/mails.php
@@ -60,7 +60,7 @@ if (isset($_POST["action"]) && $_POST["action"] == 'update')
 /*
  * Add file
  */
-if ($_POST['addfile'])
+if ($_POST['addfile'] || $_POST['addfilehtml'])
 {
 	// Set tmp user directory
 	$conf->users->dir_tmp=DOL_DATA_ROOT."/users/".$user->id;
@@ -72,9 +72,9 @@ if ($_POST['addfile'])
 	
 	    if (is_dir($upload_dir))
 	    {
-	        if (dol_move_uploaded_file($_FILES['addedfile']['tmp_name'], $upload_dir . "/" . $_FILES['addedfile']['name'],0) > 0)
+	    	if (dol_move_uploaded_file($_FILES['addedfile']['tmp_name'], $upload_dir . "/" . $_FILES['addedfile']['name'],0) > 0)
 	        {
-	            $mesg = '<div class="ok">'.$langs->trans("FileTransferComplete").'</div>';
+	        	$message = '<div class="ok">'.$langs->trans("FileTransferComplete").'</div>';
 	            //print_r($_FILES);
 
 				include_once(DOL_DOCUMENT_ROOT.'/html.formmail.class.php');
@@ -84,18 +84,20 @@ if ($_POST['addfile'])
 	        else
 	        {
 	            // Echec transfert (fichier d�passant la limite ?)
-	            $mesg = '<div class="error">'.$langs->trans("ErrorFileNotUploaded").'</div>';
+	            $message = '<div class="error">'.$langs->trans("ErrorFileNotUploaded").'</div>';
 	            // print_r($_FILES);
 	        }
 	    }
 	}
-	$_GET["action"]='test';
+	if ($_POST['addfile'])     $_GET["action"]='test';
+	if ($_POST['addfilehtml']) $_GET["action"]='testhtml';
 }
 
 /*
  * Send mail
  */
-if ($_POST['action'] == 'send' && ! $_POST['addfile'] && ! $_POST['cancel'])
+if (($_POST['action'] == 'send' || $_POST['action'] == 'sendhtml')
+	 && ! $_POST['addfile'] && ! $_POST['addfilehtml'] && ! $_POST['cancel'])
 {
 	$error=0;
 	
@@ -108,20 +110,15 @@ if ($_POST['action'] == 'send' && ! $_POST['addfile'] && ! $_POST['cancel'])
 	$subject    = $_POST['subject'];
 	$body       = $_POST['message'];
 
-	// Get list of attached files
-	$listofpaths=array();
-	$listofnames=array();
-	$listofmimes=array();
-	if (! empty($_SESSION["listofpaths"])) $listofpaths=split(';',$_SESSION["listofpaths"]);
-	if (! empty($_SESSION["listofnames"])) $listofnames=split(';',$_SESSION["listofnames"]);
-	if (! empty($_SESSION["listofmimes"])) $listofmimes=split(';',$_SESSION["listofmimes"]);
-	if (! empty($_FILES['addedfile']['tmp_name']))
-	{
-		$listofpaths[] = $_FILES['addedfile']['tmp_name'];
-		$listofnames[] = $_FILES['addedfile']['name'];
-		$listofmimes[] = $_FILES['addedfile']['type'];
-	}	
+	// Create form object
+	include_once('../html.formmail.class.php');
+	$formmail = new FormMail($db);
 
+	$attachedfiles=$formmail->get_attached_files();
+    $filepath = $attachedfiles['paths'];
+    $filename = $attachedfiles['names'];
+    $mimetype = $attachedfiles['mimes'];
+	
 	if (empty($_POST["frommail"]))
 	{
 		$message='<div class="error">'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("MailFrom")).'</div>';
@@ -137,16 +134,16 @@ if ($_POST['action'] == 'send' && ! $_POST['addfile'] && ! $_POST['cancel'])
     if (! $error)
     {
 		// Le message est-il en html
-		$msgishtml=-1;	// Unknown by default
-		if (eregi('[ \t]*<html>',$message)) $msgishtml=1;						
-
+		$msgishtml=0;	// Message is not HTML
+		if ($_POST['action'] == 'sendhtml') $msgishtml=1;	// Force message to HTML 
+		
         // Pratique les substitutions sur le sujet et message
 		$subject=make_substitutions($subject,$substitutionarrayfortest);
 		$body=make_substitutions($body,$substitutionarrayfortest);
 		
         require_once(DOL_DOCUMENT_ROOT."/lib/CMailFile.class.php");
 		$mailfile = new CMailFile($subject,$sendto,$email_from,$body,
-        							$listofpaths,$listofmimes,$listofnames,
+        							$filepath,$mimetype,$filename,
         							'', '', 0, $msgishtml,$errors_to);
         
 		$result=$mailfile->sendfile();
@@ -253,7 +250,11 @@ else
 	    print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=testconnect">'.$langs->trans("DoTestServerAvailability").'</a>';
 	}
 	print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=test&amp;mode=init">'.$langs->trans("DoTestSend").'</a>';
-    print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit">'.$langs->trans("Modify").'</a>';
+	if ($conf->fckeditor->enabled)
+	{
+		print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=testhtml&amp;mode=init">'.$langs->trans("DoTestSendHTML").'</a>';
+	}
+	print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit">'.$langs->trans("Modify").'</a>';
     print '</div>';
 	
 	
@@ -277,7 +278,7 @@ else
 			  print '<br>';
 	}
 
-	// Affichage formulaire de TEST
+	// Affichage formulaire de TEST simple
 	if ($_GET["action"] == 'test')
 	{	
 		  print '<br>';
@@ -315,11 +316,54 @@ else
 				$formmail->clear_attached_files();
 			}
 		  
-		  $formmail->show_form();
+		  $formmail->show_form('addfile');
+		  
+		  print '<br>';
+	}
+
+	// Affichage formulaire de TEST HTML
+	if ($_GET["action"] == 'testhtml')
+	{	
+		  print '<br>';
+		  print_titre($langs->trans("DoTestSendHTML"));
+		  
+		  // Cree l'objet formulaire mail
+		  include_once(DOL_DOCUMENT_ROOT."/html.formmail.class.php");
+		  $formmail = new FormMail($db);	    
+		  $formmail->fromname = $conf->global->MAIN_MAIL_EMAIL_FROM;
+		  $formmail->frommail = $conf->global->MAIN_MAIL_EMAIL_FROM;
+		  $formmail->withfromreadonly=0;
+		  $formmail->withsubstit=0;
+		  $formmail->withfrom=1;
+		  $formmail->witherrorsto=1;
+		  $formmail->withto=$user->email?$user->email:1;
+		  $formmail->withtocc=1;
+		  $formmail->withtopic=$langs->trans("Test");
+		  $formmail->withtopicreadonly=0;
+		  $formmail->withfile=2;
+		  $formmail->withbody=$langs->trans("Test");
+		  $formmail->withbodyreadonly=0;
+		  $formmail->withcancel=1;
+		  $formmail->withdeliveryreceipt=1;
+		  $formmail->withfckeditor=1;
+		  // Tableau des substitutions
+		  $formmail->substit=$substitutionarrayfortest;
+		  // Tableau des parametres complementaires du post
+		  $formmail->param["action"]="sendhtml";
+		  $formmail->param["models"]="body";
+		  $formmail->param["mailid"]=$mil->id;
+		  $formmail->param["returnurl"]=DOL_URL_ROOT."/admin/mails.php";
+		
+			// Init list of files
+			if (! empty($_REQUEST["mode"]) && $_REQUEST["mode"]=='init')
+			{
+				$formmail->clear_attached_files();
+			}
+		  
+		  $formmail->show_form('addfilehtml');
 		  
 		  print '<br>';
 	}
-	
 }
 
 
diff --git a/htdocs/html.formmail.class.php b/htdocs/html.formmail.class.php
index 5c5cfb04a57db5b943115b2e188ebbeb27bf5c34..7f08cfbbdeca5207f590707c2b5384c638fe2012 100644
--- a/htdocs/html.formmail.class.php
+++ b/htdocs/html.formmail.class.php
@@ -153,10 +153,11 @@ class FormMail
 	}
 		
 	/**
-	 *	\brief  	Affiche la partie de formulaire pour saisie d'un mail en fonction des propri�t�s
-	 * 	\remarks	this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
+	 *	\brief  		Affiche la partie de formulaire pour saisie d'un mail en fonction des propri�t�s
+	 *	\param			addfileaction		Name of action when posting file attachments	
+	 * 	\remarks		this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
 	 */
-	function show_form()
+	function show_form($addfileaction='addfile')
 	{
 		global $conf, $langs, $user;
 	
@@ -391,7 +392,7 @@ class FormMail
 				//print '<td><td align="right">';
 				print "<input type=\"file\" class=\"flat\" name=\"addedfile\" value=\"".$langs->trans("Upload")."\"/>";
 				print ' ';
-				print '<input type="submit" class="button" name="addfile" value="'.$langs->trans("MailingAddFile").'">';
+				print '<input type="submit" class="button" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'">';
 				//print '</td></tr></table>';
 			}
 			print "</td></tr>\n";
@@ -421,9 +422,20 @@ class FormMail
 			}
 			else
 			{
-				print '<textarea cols="72" rows="8" name="message">';
-				print $defaultmessage;
-				print '</textarea>';
+				if ($this->withfckeditor)
+				{
+				    // Editeur wysiwyg
+					require_once(DOL_DOCUMENT_ROOT."/lib/doleditor.class.php");
+					$doleditor=new DolEditor('message',$defaultmessage,280,'dolibarr_notes','In',true);
+					$doleditor->Create();
+				}
+				else
+				{
+					print '<textarea cols="72" rows="8" name="message">';
+					print $defaultmessage;
+					print '</textarea>';
+				}
+				
 			}
 			print "</td></tr>\n";
 		}
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index d964628ee3650b58305a0a8acab87c4f7f59ccfe..0ea6ce67ec2ff5d895049cc70243d304d24811f2 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -198,6 +198,7 @@ ServerAvailableOnIPOrPort=Server is available at address <b>%s</b> on port <b>%s
 ServerNotAvailableOnIPOrPort=Server is not available at address <b>%s</b> on port <b>%s</b>
 DoTestServerAvailability=Test server connectivity
 DoTestSend=Test sending
+DoTestSendHTML=Test sending HTML
 ErrorCantUseRazInStartedYearIfNoYearMonthInMask=Error, can't user option @ if sequence {yy}{mm} or {yyyy}{mm} is not in mask.
 
 # Modules
diff --git a/htdocs/langs/fr_FR/admin.lang b/htdocs/langs/fr_FR/admin.lang
index bc3ae64047945c95d228328c035af03b54f2a7e3..83c3de80e7ba81a9d685e185f1f80ec3fae45f91 100644
--- a/htdocs/langs/fr_FR/admin.lang
+++ b/htdocs/langs/fr_FR/admin.lang
@@ -197,6 +197,7 @@ ServerAvailableOnIPOrPort=Serveur disponible a l'adresse <b>%s</b> sur le port <
 ServerNotAvailableOnIPOrPort=Serveur non disponible � l'adresse <b>%s</b> sur le port <b>%s</b>
 DoTestServerAvailability=Tester disponibilit� serveur
 DoTestSend=Tester envoi
+DoTestSendHTML=Tester envoi HTML
 ErrorCantUseRazInStartedYearIfNoYearMonthInMask=Erreur, ne peut utiliser l'option @ si la s�quence {yy}{mm} ou {yyyy}{mm} n'est pas dans le masque.
 
 # Modules
diff --git a/htdocs/lib/CMailFile.class.php b/htdocs/lib/CMailFile.class.php
index 3c58e9aac635cca31c1c0bba140d20146457788c..fb73ddb820fbd3ae627c369c5fbf2864b863c16a 100644
--- a/htdocs/lib/CMailFile.class.php
+++ b/htdocs/lib/CMailFile.class.php
@@ -73,6 +73,8 @@ class CMailFile
     {
         dolibarr_syslog("CMailFile::CMailfile: from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to");
         dolibarr_syslog("CMailFile::CMailfile: subject=$subject, deliveryreceipt=$deliveryreceipt, msgishtml=$msgishtml");
+
+        // Define if there is at least one file
         foreach ($filename_list as $i => $val)
         {
         	if ($filename_list[$i])
@@ -90,7 +92,7 @@ class CMailFile
 		if (eregi('^win',PHP_OS)) $this->eol="\r\n";
 		if (eregi('^mac',PHP_OS)) $this->eol="\r";
 
-		// Detect if message is HTML
+		// Detect if message is HTML (use fast method)
 		if ($msgishtml == -1)
 		{
 			$this->msgishtml = 0;
@@ -132,11 +134,10 @@ class CMailFile
         }
 
 		// On defini $this->headers et $this->message
-		//$this->headers = $smtp_headers . $mime_headers . $this->eol;
-		//$this->message = $text_body . $text_encoded . $this->eol;
         $this->headers = $smtp_headers . $mime_headers;
         $this->message = $text_body . $text_encoded;
-		// On nettoie le header pour qu'il ne se termine pas un retour chariot.
+
+        // On nettoie le header pour qu'il ne se termine pas par un retour chariot.
 		// Ceci evite aussi les lignes vides en fin qui peuvent etre interpretees 
 		// comme des injections mail par les serveurs de messagerie.
 		$this->headers = eregi_replace("[\r\n]+$","",$this->headers);
@@ -177,7 +178,7 @@ class CMailFile
 		dolibarr_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject);
 		dolibarr_syslog("CMailFile::sendfile header=\n".$this->headers);
 		//dolibarr_syslog("CMailFile::sendfile message=\n".$message);
-		//$this->dump_mail();
+		$this->dump_mail();
 
 		$errorlevel=error_reporting();
 		error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
@@ -245,10 +246,13 @@ class CMailFile
      */
     function dump_mail()
     {
-    	if (@is_writeable("/tmp"))	// Avoid fatal error on fopen with open_basedir
+    	global $dolibarr_main_data_root;
+    	
+    	if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
     	{
-        	$fp = fopen("/tmp/dolibarr_mail","w");
+        	$fp = fopen($dolibarr_main_data_root."/dolibarr_mail","w");
         	fputs($fp, $this->headers);
+        	fputs($fp, $this->eol);			// This eol is added by the mail function, so we add it in log
         	fputs($fp, $this->message);
         	fclose($fp);
     	}
@@ -282,12 +286,13 @@ class CMailFile
        
         if ($this->msgishtml)
         {
-        	$out.= "Content-Type: text/html; charset=".$conf->character_set_client.$this->eol;
+        	if (! $this->atleastonefile) $out.= "Content-Type: text/html; charset=".$conf->character_set_client.$this->eol;
         	$out.= "Content-Transfer-Encoding: 8bit".$this->eol;
         }
         else
         {
-			$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
+        	if (! $this->atleastonefile) $out.= "Content-Type: text/plain; charset=".$conf->character_set_client.$this->eol;
+        	$out.= "Content-Transfer-Encoding: 8bit".$this->eol;
 		}
 
         dolibarr_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
@@ -338,11 +343,11 @@ class CMailFile
             $out.= "--" . $this->mime_boundary . $this->eol;
 	        if ($this->msgishtml)
 	        {
-	        	$out.= "Content-Type: text/html; charset=".$conf->charset_output.$this->eol;
+	        	$out.= "Content-Type: text/html; charset=".$conf->character_set_client.$this->eol;
 	        }
 	        else
 	        {
-	        	$out.= "Content-Type: text/plain; charset=".$conf->charset_output.$this->eol;	        	
+	        	$out.= "Content-Type: text/plain; charset=".$conf->character_set_client.$this->eol;	        	
 	        }
             $out.= $this->eol;
         }
diff --git a/htdocs/lib/functions.lib.php b/htdocs/lib/functions.lib.php
index 5269d5c2624b172206f19863f1f9611a353dab33..16eb7f74448b8cc6ef2cf41a64342402ab815be9 100644
--- a/htdocs/lib/functions.lib.php
+++ b/htdocs/lib/functions.lib.php
@@ -1217,7 +1217,7 @@ function img_mime($file)
 	if (eregi('\.(png|bmp|jpg|jpeg|gif)',$file)) $mime='image';
 	if (eregi('\.(mp3|ogg|au)',$file))           $mime='audio';
 	if (eregi('\.(avi|mvw|divx|xvid)',$file))    $mime='video';
-	if (eregi('\.(zip|rar|divx|xvid)',$file))    $mime='archive';
+	if (eregi('\.(zip|rar|gz|tgz|z|cab)',$file))       $mime='archive';
 	$alt='Mime type: '.$mime;
 	
 	$mime.='.png';