diff --git a/smtp.php b/smtp.php index 6a57559..bd9d119 100644 --- a/smtp.php +++ b/smtp.php @@ -21,6 +21,10 @@ class smtp /** The Timeout between the answer of the SMTP server. If the server don't * answer in this time, an exception is raised */ public $timeout = 10; + /** Activate STARTTLS if needed. Allowed values : none, may, encrypt*/ + public $starttls = "may"; + /** The authentication methods in an array. Allowed : plain, login*/ + public $authmethods = array ("plain", "login"); /** The socket of the connection */ private $smtpStream = null; @@ -40,13 +44,43 @@ class smtp // Wait for banner $banner = $this->getLine ("SMTP Banner"); // Send EHLO - $this->putLine ("EHLO ".gethostname ()."\r\n"); + $features = $this->putLine ("EHLO ".gethostname ()."\r\n"); + $features = explode ("\r\n", $features); + if (in_array ("250-STARTTLS", $features)) + { + // Server supports STARTTLS + if ($this->starttls === "may" || $this->starttls === "encrypt") + { + $this->putLine ("STARTTLS\r\n"); + stream_socket_enable_crypto ($this->smtpStream, true, + STREAM_CRYPTO_METHOD_TLS_CLIENT); + } + } + elseif ($this->starttls === "encrypt") + throw new \Exception (_("Server doesn't supports STARTTLS"), 500); + if ($this->user !== null && $this->password !== null) { - // Send User and password AUTH PLAIN - $this->putLine ("AUTH PLAIN ". - base64_encode ($this->user.chr(0).$this->user.chr(0). - $this->password)."\r\n"); + $auths = preg_grep ("#^250-AUTH #", $features); + $auths = reset ($auths); + if (strpos ($auths, "PLAIN") && in_array ("plain", $this->authmethods)) + { + // Send User and password AUTH PLAIN + $this->putLine ("AUTH PLAIN ". + base64_encode ($this->user.chr(0).$this->user.chr(0). + $this->password)."\r\n"); + } + elseif (strpos ($auths, "LOGIN") && + in_array ("login", $this->authmethods)) + { + // Send User and password AUTH LOGIN + $this->putLine ("AUTH LOGIN ".base64_encode ($this->user)."\r\n"); + $this->putLine (base64_encode ($this->password)."\r\n"); + } + else + throw new \Exception ( + _("No authentication method available for the server"), + 500); } } @@ -116,7 +150,7 @@ class smtp $this->debug ("Timeout when waiting $message\n"); throw new \Exception ("Timeout when waiting $message", 500); } - $content .= $line; + $content .= $line."\r\n"; if (substr ($line, 3, 1) === " ") break; }