diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php
index 9a16dcadc081edb87ac2e36e89606940ea8e1cf0..0a945a64e5963f60f961e9e317475bdff41cf297 100644
--- a/htdocs/admin/mails.php
+++ b/htdocs/admin/mails.php
@@ -52,8 +52,9 @@ if (isset($_POST["action"]) && $_POST["action"] == 'update')
 	dolibarr_set_const($db, "MAIN_MAIL_SENDMODE",       $_POST["MAIN_MAIL_SENDMODE"],'chaine',0,'',0);
 	dolibarr_set_const($db, "MAIN_MAIL_SMTP_PORT",      $_POST["MAIN_MAIL_SMTP_PORT"],'chaine',0,'',0);
 	dolibarr_set_const($db, "MAIN_MAIL_SMTP_SERVER",    $_POST["MAIN_MAIL_SMTP_SERVER"],'chaine',0,'',0);
-	if (isset($_POST["MAIN_MAIL_SMTPS_ID"])) dolibarr_set_const($db, "MAIN_MAIL_SMTPS_ID",       $_POST["MAIN_MAIL_SMTPS_ID"],'chaine',0,'',0);
-	if (isset($_POST["MAIN_MAIL_SMTPS_PW"])) dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW",       $_POST["MAIN_MAIL_SMTPS_PW"],'chaine',0,'',0);
+	if (isset($_POST["MAIN_MAIL_SMTPS_ID"]))  dolibarr_set_const($db, "MAIN_MAIL_SMTPS_ID",  $_POST["MAIN_MAIL_SMTPS_ID"],'chaine',0,'',0);
+	if (isset($_POST["MAIN_MAIL_SMTPS_PW"]))  dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW",  $_POST["MAIN_MAIL_SMTPS_PW"],'chaine',0,'',0);
+	if (isset($_POST["MAIN_MAIL_EMAIL_TLS"])) dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS", $_POST["MAIN_MAIL_EMAIL_TLS"],'chaine',0,'',0);
 	dolibarr_set_const($db, "MAIN_MAIL_EMAIL_FROM",     $_POST["MAIN_MAIL_EMAIL_FROM"],'chaine',0,'',$conf->entity);
 
 	Header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup");
@@ -190,7 +191,8 @@ if (! $server) $server='127.0.0.1';
  * View
  */
 
-llxHeader();
+$wikihelp='EN:First_setup|FR:Premiers_paramétrages|ES:Primeras_configuraciones';
+llxHeader($langs->trans("Setup"),'',$wikihelp);
 
 print_fiche_titre($langs->trans("EMailsSetup"),'','setup');
 
@@ -199,6 +201,12 @@ print "<br>\n";
 
 if ($message) print $message.'<br>';
 
+// List of sending methods
+$listofmethods=array();
+$listofmethods['mail']='PHP mail function';
+$listofmethods['simplemail']='Simplemail class';
+$listofmethods['smtps']='SMTP/SMTPS socket library';
+
 
 if (isset($_GET["action"]) && $_GET["action"] == 'edit')
 {
@@ -223,10 +231,7 @@ if (isset($_GET["action"]) && $_GET["action"] == 'edit')
 	// Method
 	$var=!$var;
 	print '<tr '.$bc[$var].'><td>'.$langs->trans("MAIN_MAIL_SENDMODE").'</td><td>';
-	$listofmethods=array();
-	$listofmethods['mail']='PHP mail function';
-	$listofmethods['simplemail']='Simplemail class';
-	$listofmethods['smtps']='SMTP/SMTP-AUTH socket library';
+
 	// SuperAdministrator access only
 	if ((empty($conf->global->MAIN_MODULE_MULTICOMPANY)) || ($user->admin && !$user->entity))
 	{
@@ -234,10 +239,8 @@ if (isset($_GET["action"]) && $_GET["action"] == 'edit')
 	}
 	else
 	{
-		if ($conf->global->MAIN_MAIL_SENDMODE == 'mail') $text = 'PHP mail function';
-		elseif ($conf->global->MAIN_MAIL_SENDMODE == 'simplemail') $text = 'Simplemail class';
-		elseif ($conf->global->MAIN_MAIL_SENDMODE == 'smtps') $text = 'SMTPS library';
-		else { $text = $langs->trans("Undefined"); }
+		$text = $listofmethods[$conf->global->MAIN_MAIL_SENDMODE];
+		if (empty($text)) $text = $langs->trans("Undefined");
 		$htmltext = $langs->trans("ContactSuperAdminForChange");
 		print $html->textwithpicto($text,$htmltext,1,'superadmin');
 		print '<input type="hidden" name="MAIN_MAIL_SENDMODE" value="'.$conf->global->MAIN_MAIL_SENDMODE.'">';
@@ -343,8 +346,15 @@ if (isset($_GET["action"]) && $_GET["action"] == 'edit')
 	// TLS
 	$var=!$var;
 	print '<tr '.$bc[$var].'><td>'.$langs->trans("MAIN_MAIL_EMAIL_TLS").'</td><td>';
-	//print '<input class="flat" name="MAIN_MAIL_EMAIL_TLS" size="32" value="'.$conf->global->MAIN_MAIL_EMAIL_TLS.'">';
-	print $langs->trans("NotSupported");
+	if ($conf->global->MAIN_MAIL_SENDMODE == 'smtps')
+	{
+		if (function_exists('openssl_open'))
+		{
+			print $html->selectyesno('MAIN_MAIL_EMAIL_TLS',$conf->global->MAIN_MAIL_EMAIL_TLS,1);
+		}
+		else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')';
+	}
+	else print yn(0).' ('.$langs->trans("NotSupported").')';
 	print '</td></tr>';
 
 	// From
@@ -374,10 +384,9 @@ else
 	// Method
 	$var=!$var;
 	print '<tr '.$bc[$var].'><td>'.$langs->trans("MAIN_MAIL_SENDMODE").'</td><td>';
-	if ($conf->global->MAIN_MAIL_SENDMODE == 'mail') print 'PHP mail function';
-	elseif ($conf->global->MAIN_MAIL_SENDMODE == 'simplemail') print 'Simplemail class';
-	elseif ($conf->global->MAIN_MAIL_SENDMODE == 'smtps') print 'SMTPS library';
-	else { print $langs->trans("Undefined"); }
+	$text=$listofmethods[$conf->global->MAIN_MAIL_SENDMODE];
+	if (empty($text)) $text=$langs->trans("Undefined");
+	print $text;
 	print '</td></tr>';
 
 	// Server
@@ -419,8 +428,15 @@ else
 	// TLS
 	$var=!$var;
 	print '<tr '.$bc[$var].'><td>'.$langs->trans("MAIN_MAIL_EMAIL_TLS").'</td><td>';
-	//print '<input class="flat" name="MAIN_MAIL_EMAIL_TLS" size="32" value="'.$conf->global->MAIN_MAIL_EMAIL_TLS.'">';
-	print $langs->trans("NotSupported");
+	if ($conf->global->MAIN_MAIL_SENDMODE == 'smtps')
+	{
+		if (function_exists('openssl_open'))
+		{
+			print yn($conf->global->MAIN_MAIL_EMAIL_TLS);
+		}
+		else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')';
+	}
+	else print yn(0).' ('.$langs->trans("NotSupported").')';
 	print '</td></tr>';
 
 	// From
@@ -458,13 +474,15 @@ else
 	print '</div>';
 
 
-	// Affichage formulaire de TEST
+	// Run the test to connect
 	if ($_GET["action"] == 'testconnect')
 	{
 		print '<br>';
 		print_titre($langs->trans("DoTestServerAvailability"));
 
-		// Cree l'objet formulaire mail
+		// If we use SSL/TLS
+		if (! empty($conf->global->MAIN_MAIL_EMAIL_TLS)) $server='ssl://'.$server;
+
 		include_once(DOL_DOCUMENT_ROOT."/lib/CMailFile.class.php");
 		$mail = new CMailFile('','','','');
 		$result=$mail->check_server_port($server,$port);
diff --git a/htdocs/includes/smtps/SMTPs.php b/htdocs/includes/smtps/SMTPs.php
index 20743583bc6bfada6154c247b58ba23db9d63810..cde3a4c313d27ee111e91c52137634d2385659ac 100644
--- a/htdocs/includes/smtps/SMTPs.php
+++ b/htdocs/includes/smtps/SMTPs.php
@@ -624,9 +624,12 @@ class SMTPs
         // We have to make sure the HOST given is valid
         // This is done here because '@fsockopen' will not give me this
         // information if it failes to connect because it can't find the HOST
-        if ( (gethostbyname ( $this->getHost() )) == $this->getHost() )
+        $host=$this->getHost();
+        $host=preg_replace('@tcp://@i','',$host);	// Remove prefix
+        $host=preg_replace('@ssl://@i','',$host);	// Remove prefix
+        if ( (gethostbyname ( $host )) == $host )
         {
-            $this->_setErr ( 99, $this->getHost() . ' is either offline or is an invalid host name.' );
+            $this->_setErr ( 99, $host . ' is either offline or is an invalid host name.' );
             $_retVal = false;
         }
         else
@@ -642,8 +645,7 @@ class SMTPs
                 // Sometimes the SMTP server takes a little longer to respond
                 // so we will give it a longer timeout for the first read
                 // Windows still does not have support for this timeout function
-                if( function_exists('socket_set_timeout') )
-                    socket_set_timeout($this->socket, $this->_smtpTimeout, 0);
+                if (function_exists('stream_set_timeout')) stream_set_timeout($this->socket, $this->_smtpTimeout, 0);
 
                 // Check response from Server
                 if ( $_retVal = $this->server_parse($this->socket, "220") )
@@ -684,7 +686,10 @@ class SMTPs
         // Send the RFC2554 specified EHLO.
         // This improvment as provided by 'SirSir' to
         // accomodate both SMTP AND ESMTP capable servers
-        if ( $_retVal = $this->socket_send_str('EHLO ' . $this->getHost(), '250') )
+        $host=$this->getHost();
+        $host=preg_replace('@tcp://@i','',$host);	// Remove prefix
+        $host=preg_replace('@ssl://@i','',$host);	// Remove prefix
+    	if ( $_retVal = $this->socket_send_str('EHLO ' . $host, '250') )
         {
             // Send Authentication to Server
             // Check for errors along the way
@@ -700,7 +705,7 @@ class SMTPs
         }
         else
         {
-            $this->_setErr ( 126, '"' . $this->getHost() . '" does not support secure connections.' );
+            $this->_setErr ( 126, '"' . $host . '" does not support authenticated connections.' );
         }
 
         return $_retVal;
@@ -753,7 +758,10 @@ class SMTPs
             else
             {
                 // Send the RFC821 specified HELO.
-                $_retVal = $this->socket_send_str('HELO ' . $this->getHost(), '250');
+		        $host=$this->getHost();
+		        $host=preg_replace('@tcp://@i','',$host);	// Remove prefix
+		        $host=preg_replace('@ssl://@i','',$host);	// Remove prefix
+            	$_retVal = $this->socket_send_str('HELO ' . $host, '250');
             }
 
             // Well, did we get to the server?
@@ -1854,10 +1862,14 @@ class SMTPs
         if ( $this->getBCC() )
             $_header .= 'Bcc: ' . $this->getBCC()  . "\r\n";
 
+        $host=$this->getHost();
+        $host=preg_replace('@tcp://@i','',$host);	// Remove prefix
+        $host=preg_replace('@ssl://@i','',$host);	// Remove prefix
+
         //NOTE: Message-ID should probably contain the username of the user who sent the msg
         $_header .= 'Subject: '    . $this->getSubject()     . "\r\n"
                  .  'Date: '       . date("r")               . "\r\n"
-                 .  'Message-ID: <' . time() . '.SMTPs@' . $this->getHost() . ">\r\n";
+                 .  'Message-ID: <' . time() . '.SMTPs@' . $host . ">\r\n";
 //                 . 'Read-Receipt-To: '   . $this->getFrom( 'org' ) . "\r\n"
 //                 . 'Return-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n";
 
@@ -1963,7 +1975,7 @@ class SMTPs
             $content = 'Content-Type: ' . $_msgData['mimeType'] . '; charset="' . $this->getCharSet() . '"' . "\r\n"
                      . 'Content-Transfer-Encoding: ' . $this->getTransEncodeType() . "\r\n"
                      . 'Content-Disposition: inline'  . "\r\n"
-                     . 'Content-Description: ' . $this->_msgContent[0] . ' message' . "\r\n";
+                     . 'Content-Description: message' . "\r\n";
 
             if ( $this->getMD5flag() )
                 $content .= 'Content-MD5: ' . $_msgData['md5'] . "\r\n";
@@ -2499,6 +2511,9 @@ class SMTPs
 
  /**
   * $Log$
+  * Revision 1.10  2009/11/01 14:16:30  eldy
+  * Fix: Sending mail with SMTPS was not working.
+  *
   * Revision 1.9  2009/10/20 13:14:47  hregis
   * Fix: function "split" is deprecated since php 5.3.0
   *
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index 0f2171995aa4b05d04850302bb5d67e00aaee3ad..4283ac53c99104fe615cc8e1ec92d5a123b3b04f 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -726,6 +726,7 @@ PreviousDumpFiles=Available database backup dump files
 WeekStartOnDay=First day of week 
 RunningUpdateProcessMayBeRequired=Running the upgrade process seems to be required (Programs version %s differs from database version %s)
 YouMustRunCommandFromCommandLineAfterLoginToUser=You must run this command from command line after login to a shell with user <b>%s</b>.
+YourPHPDoesNotHaveSSLSupport=SSL functions not available in your PHP
 
 ##### Module password generation
 PasswordGenerationStandard=Return a password generated according to internal Dolibarr algorithm: 8 characters containing shared numbers and characters in lowercase.
diff --git a/htdocs/langs/fr_FR/admin.lang b/htdocs/langs/fr_FR/admin.lang
index f4f68352fd6f0f3c55bb1db1527f55bdba2868bf..25933440112e9464bdd8ae72cc87f03ca6a64463 100644
--- a/htdocs/langs/fr_FR/admin.lang
+++ b/htdocs/langs/fr_FR/admin.lang
@@ -726,6 +726,7 @@ PreviousDumpFiles=Fichiers disponibles de sauvegarde de la base de donnée
 WeekStartOnDay=Premier jour de la semaine
 RunningUpdateProcessMayBeRequired=Le lancement du processus de mise a jour semble requis (La version des programme %s differe de la version de la base %s)
 YouMustRunCommandFromCommandLineAfterLoginToUser=Vous devez exécuter la commande sous un shell après vous etres logués avec le compte <b>%s</b>.
+YourPHPDoesNotHaveSSLSupport=Fonctions SSL non présentes dans votre PHP
 
 ##### Module password generation = undefined
 PasswordGenerationStandard = Renvoie un mot de passe généré selon algorithme interne Dolibarr: 8 caractères, chiffres et caractères en minuscules mélangés.
diff --git a/htdocs/lib/CMailFile.class.php b/htdocs/lib/CMailFile.class.php
index b4e83f8cc8b2fd5d80349d7f5e7a7cf25b556fe9..b275556befdbb563397484b26872d4d1ccc12f9f 100644
--- a/htdocs/lib/CMailFile.class.php
+++ b/htdocs/lib/CMailFile.class.php
@@ -421,12 +421,12 @@ class CMailFile
 				$dest=$this->getValidAddress($this->addr_to,2);
 				if (! $dest)
 				{
-					$this->error="Failed to send mail to SMTP=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
+					$this->error="Failed to send mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERROR);
 				}
 				else
 				{
-					dol_syslog("CMailFile::sendfile: mail start SMTP=".ini_get('SMTP').", PORT=".ini_get('smtp_port'), LOG_DEBUG);
+					dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'), LOG_DEBUG);
 
 					$bounce = '';
 					if ($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)
@@ -445,7 +445,7 @@ class CMailFile
 
 					if (! $res)
 					{
-						$this->error="Failed to send mail to SMTP=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Check your server logs and your firewalls setup";
+						$this->error="Failed to send mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Check your server logs and your firewalls setup";
 						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERROR);
 					}
 					else
@@ -482,7 +482,7 @@ class CMailFile
 				if (! empty($conf->global->MAIN_MAIL_SMTP_SERVER)) ini_set('SMTP',$conf->global->MAIN_MAIL_SMTP_SERVER);
 				if (! empty($conf->global->MAIN_MAIL_SMTP_PORT))   ini_set('smtp_port',$conf->global->MAIN_MAIL_SMTP_PORT);
 
-				dol_syslog("CMailFile::sendfile: mail start SMTP=".ini_get('SMTP').", PORT=".ini_get('smtp_port'), LOG_DEBUG);
+				dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'), LOG_DEBUG);
 
 				$this->message=stripslashes($this->message);
 
@@ -492,7 +492,7 @@ class CMailFile
 
 				if (! $res)
 				{
-					$this->error="Failed to send mail to SMTP=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Check your server logs and your firewalls setup";
+					$this->error="Failed to send mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Check your server logs and your firewalls setup";
 					dol_syslog("CMailFile::sendfile: mail end error ".$this->error, LOG_ERR);
 					dol_syslog("CMailFile::sendfile: ".$this->simplemail->error_log, LOG_ERR);
 				}
@@ -522,8 +522,12 @@ class CMailFile
 				if (empty($conf->global->MAIN_MAIL_SMTP_SERVER)) $conf->global->MAIN_MAIL_SMTP_SERVER=ini_get('SMTP');
 				if (empty($conf->global->MAIN_MAIL_SMTP_PORT))   $conf->global->MAIN_MAIL_SMTP_PORT=ini_get('smtp_port');
 
-				$this->smtps->setHost($conf->global->MAIN_MAIL_SMTP_SERVER);
-				$this->smtps->setPort($conf->global->MAIN_MAIL_SMTP_PORT); //587 or 25;
+				// If we use SSL/TLS
+				$server=$conf->global->MAIN_MAIL_SMTP_SERVER;
+				if (! empty($conf->global->MAIN_MAIL_EMAIL_TLS)) $server='ssl://'.$server;
+
+				$this->smtps->setHost($server);
+				$this->smtps->setPort($conf->global->MAIN_MAIL_SMTP_PORT); // 25, 465...;
 
 				if (! empty($conf->global->MAIN_MAIL_SMTPS_ID)) $this->smtps->setID($conf->global->MAIN_MAIL_SMTPS_ID);
 				if (! empty($conf->global->MAIN_MAIL_SMTPS_PW)) $this->smtps->setPW($conf->global->MAIN_MAIL_SMTPS_PW);
@@ -532,7 +536,7 @@ class CMailFile
 				$dest=$this->smtps->getFrom('org');
 				if (! $dest)
 				{
-					$this->error="Failed to send mail to SMTP=".$conf->global->MAIN_MAIL_SMTP_SERVER.", PORT=".$conf->global->MAIN_MAIL_SMTP_PORT."<br>Recipient address '$dest' invalid";
+					$this->error="Failed to send mail to HOST=".$server.", PORT=".$conf->global->MAIN_MAIL_SMTP_PORT."<br>Recipient address '$dest' invalid";
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
 				}
 				else
@@ -727,11 +731,11 @@ class CMailFile
 		}
 
 		// Make RFC821 Compliant, replace bare linefeeds
-    $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $strContent );
+		$strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $strContent );
 
-    $strContent = rtrim(wordwrap($strContent));
+		$strContent = rtrim(wordwrap($strContent));
 
-    $out.=$strContent.$this->eol;
+		$out.=$strContent.$this->eol;
 
 		return $out;
 	}
@@ -787,7 +791,7 @@ class CMailFile
 			$out.= '</style>';
 		}
 
-	  return $out;
+		return $out;
 	}
 
 	/**
@@ -863,28 +867,35 @@ class CMailFile
 	}
 
 
+	/**
+	 * Try to create a socket connection
+	 *
+	 * @param 		unknown_type $host. Add ssl:// for SSL/TLS.
+	 * @param 		unknown_type $port. Example: 25, 465
+	 * @return 		Socket id if ok, 0 if KO
+	 */
 	function check_server_port($host,$port)
 	{
 		$_retVal=0;
+		$timeout=5;	// Timeout in seconds
 
 		if (function_exists('fsockopen'))
 		{
 			dol_syslog("Try socket connection to host=".$host." port=".$port);
 			//See if we can connect to the SMTP server
-			if ( $socket = @fsockopen($host,       // Host to 'hit', IP or domain
+			if ( $socket = @fsockopen($host,       // Host to test, IP or domain. Add ssl:// for SSL/TLS.
 			$port,       // which Port number to use
-			$errno,           // actual system level error
-			$errstr,          // and any text that goes with the error
-			5) )  // timeout for reading/writing data over the socket
+			$errno,      // actual system level error
+			$errstr,     // and any text that goes with the error
+			$timeout) )  // timeout for reading/writing data over the socket
 			{
 				// Windows still does not have support for this timeout function
-				if (function_exists('socket_set_timeout')) socket_set_timeout($socket, 5, 0);
+				if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0);
 
 				dol_syslog("Now we wait for answer 220");
 
 				// Check response from Server
-				if ( $_retVal = $this->server_parse($socket, "220") )
-				$_retVal = $socket;
+				if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
 			}
 			else
 			{
@@ -896,7 +907,7 @@ class CMailFile
 
 	// This function has been modified as provided
 	// by SirSir to allow multiline responses when
-	// using SMTP Extensions
+	// using SMTP Extensions.
 	//
 	function server_parse($socket, $response)
 	{
@@ -932,9 +943,9 @@ class CMailFile
 	}
 
 	/**
-	 \brief 		Recherche la presence d'images dans le message html
-	 \param 		images_dir		Emplacement des images
-	 \return		int         	>0 if OK, <0 if KO
+	 *	\brief 		Recherche la presence d'images dans le message html
+	 *	\param 		images_dir		Emplacement des images
+	 *	\return		int         	>0 if OK, <0 if KO
 	 */
 	function findHtmlImages($images_dir)
 	{