diff --git a/src/wp-includes/class-phpmailer.php b/src/wp-includes/class-phpmailer.php
index c38632a..059ec28 100644
--- a/src/wp-includes/class-phpmailer.php
+++ b/src/wp-includes/class-phpmailer.php
@@ -1,15 +1,14 @@
 <?php
 /**
  * PHPMailer - PHP email creation and transport class.
- * PHP Version 5.0.0
- * Version 5.2.7
+ * PHP Version 5
  * @package PHPMailer
- * @link https://github.com/PHPMailer/PHPMailer/
- * @author Marcus Bointon (coolbru) <phpmailer@synchromedia.co.uk>
+ * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
+ * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  * @author Brent R. Matzelle (original founder)
- * @copyright 2013 Marcus Bointon
+ * @copyright 2012 - 2014 Marcus Bointon
  * @copyright 2010 - 2012 Jim Jagielski
  * @copyright 2004 - 2009 Andy Prevost
  * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
@@ -18,21 +17,13 @@
  * FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-if (version_compare(PHP_VERSION, '5.0.0', '<')) {
-    exit("Sorry, PHPMailer will only run on PHP version 5 or greater!\n");
-}
-
 /**
  * PHPMailer - PHP email creation and transport class.
- * PHP Version 5.0.0
  * @package PHPMailer
- * @author Marcus Bointon (coolbru) <phpmailer@synchromedia.co.uk>
+ * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  * @author Brent R. Matzelle (original founder)
- * @copyright 2013 Marcus Bointon
- * @copyright 2010 - 2012 Jim Jagielski
- * @copyright 2004 - 2009 Andy Prevost
  */
 class PHPMailer
 {
@@ -40,7 +31,7 @@ class PHPMailer
      * The PHPMailer Version number.
      * @type string
      */
-    public $Version = '5.2.7';
+    public $Version = '5.2.8';
 
     /**
      * Email priority.
@@ -97,6 +88,9 @@ class PHPMailer
      * The Return-Path of the message.
      * If empty, it will be set to either From or Sender.
      * @type string
+     * @deprecated Email senders should never set a return-path header;
+     * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
+     * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
      */
     public $ReturnPath = '';
 
@@ -299,19 +293,27 @@ class PHPMailer
 
     /**
      * SMTP class debug output mode.
-     * Options: 0 = off, 1 = commands, 2 = commands and data
+     * Options:
+     *   0: no output
+     *   1: commands
+     *   2: data and commands
+     *   3: as 2 plus connection status
+     *   4: low level data output
      * @type int
      * @see SMTP::$do_debug
      */
     public $SMTPDebug = 0;
 
     /**
-     * The function/method to use for debugging output.
-     * Options: "echo" or "error_log"
+     * How to handle debug output.
+     * Options:
+     *   'echo': Output plain-text as-is, appropriate for CLI
+     *   'html': Output escaped, line breaks converted to <br>, appropriate for browser output
+     *   'error_log': Output to error log as configured in php.ini
      * @type string
      * @see SMTP::$Debugoutput
      */
-    public $Debugoutput = "echo";
+    public $Debugoutput = 'echo';
 
     /**
      * Whether to keep SMTP connection open after each message.
@@ -339,6 +341,7 @@ class PHPMailer
      * Whether to generate VERP addresses on send.
      * Only applicable when sending via SMTP.
      * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
+     * @link http://www.postfix.org/VERP_README.html Postfix VERP info
      * @type bool
      */
     public $do_verp = false;
@@ -396,11 +399,7 @@ class PHPMailer
      * The function that handles the result of the send email action.
      * It is called out by send() for each email sent.
      *
-     * Value can be:
-     * - 'function_name' for function names
-     * - 'Class::Method' for static method calls
-     * - array($object, 'Method') for calling methods on $object
-     * See http://php.net/is_callable manual page for more details.
+     * Value can be any php callable: http://www.php.net/is_callable
      *
      * Parameters:
      *   bool    $result        result of the send action
@@ -410,7 +409,6 @@ class PHPMailer
      *   string  $subject       the subject
      *   string  $body          the email body
      *   string  $from          email address of sender
-     * 
      * @type string
      */
     public $action_function = '';
@@ -597,12 +595,18 @@ class PHPMailer
      */
     private function mailPassthru($to, $subject, $body, $header, $params)
     {
+        //Check overloading of mail function to avoid double-encoding
+        if (ini_get('mbstring.func_overload') & 1) {
+            $subject = $this->secureHeader($subject);
+        } else {
+            $subject = $this->encodeHeader($this->secureHeader($subject));
+        }
         if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
-            $rt = @mail($to, $this->encodeHeader($this->secureHeader($subject)), $body, $header);
+            $result = @mail($to, $subject, $body, $header);
         } else {
-            $rt = @mail($to, $this->encodeHeader($this->secureHeader($subject)), $body, $header, $params);
+            $result = @mail($to, $subject, $body, $header, $params);
         }
-        return $rt;
+        return $result;
     }
 
     /**
@@ -627,8 +631,7 @@ class PHPMailer
                 break;
             case 'echo':
             default:
-                //Just echoes exactly what was received
-                echo $str;
+                echo $str."\n";
         }
     }
 
@@ -670,8 +673,12 @@ class PHPMailer
      */
     public function isSendmail()
     {
-        if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
-            $this->Sendmail = '/var/qmail/bin/sendmail';
+        $ini_sendmail_path = ini_get('sendmail_path');
+        
+        if (!stristr($ini_sendmail_path, 'sendmail')) {
+            $this->Sendmail = '/usr/sbin/sendmail';
+        } else {
+            $this->Sendmail = $ini_sendmail_path;
         }
         $this->Mailer = 'sendmail';
     }
@@ -682,10 +689,14 @@ class PHPMailer
      */
     public function isQmail()
     {
-        if (stristr(ini_get('sendmail_path'), 'qmail')) {
-            $this->Sendmail = '/var/qmail/bin/sendmail';
+        $ini_sendmail_path = ini_get('sendmail_path');
+        
+        if (!stristr($ini_sendmail_path, 'qmail')) {
+            $this->Sendmail = '/var/qmail/bin/qmail-inject';
+        } else {
+            $this->Sendmail = $ini_sendmail_path;
         }
-        $this->Mailer = 'sendmail';
+        $this->Mailer = 'qmail';
     }
 
     /**
@@ -748,20 +759,20 @@ class PHPMailer
     {
         if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
             $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
+            $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
             if ($this->exceptions) {
                 throw new phpmailerException('Invalid recipient array: ' . $kind);
             }
-            $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
             return false;
         }
         $address = trim($address);
         $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
         if (!$this->validateAddress($address)) {
             $this->setError($this->lang('invalid_address') . ': ' . $address);
+            $this->edebug($this->lang('invalid_address') . ': ' . $address);
             if ($this->exceptions) {
                 throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
             }
-            $this->edebug($this->lang('invalid_address') . ': ' . $address);
             return false;
         }
         if ($kind != 'Reply-To') {
@@ -793,10 +804,10 @@ class PHPMailer
         $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
         if (!$this->validateAddress($address)) {
             $this->setError($this->lang('invalid_address') . ': ' . $address);
+            $this->edebug($this->lang('invalid_address') . ': ' . $address);
             if ($this->exceptions) {
                 throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
             }
-            $this->edebug($this->lang('invalid_address') . ': ' . $address);
             return false;
         }
         $this->From = $address;
@@ -825,22 +836,20 @@ class PHPMailer
      * Check that a string looks like an email address.
      * @param string $address The email address to check
      * @param string $patternselect A selector for the validation pattern to use :
-     *   'auto' - pick best one automatically;
-     *   'pcre8' - use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
-     *   'pcre' - use old PCRE implementation;
-     *   'php' - use PHP built-in FILTER_VALIDATE_EMAIL; faster, less thorough;
-     *   'noregex' - super fast, really dumb.
+     * * `auto` Pick strictest one automatically;
+     * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
+     * * `pcre` Use old PCRE implementation;
+     * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; same as pcre8 but does not allow 'dotless' domains;
+     * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
+     * * `noregex` Don't use a regex: super fast, really dumb.
      * @return bool
      * @static
      * @access public
      */
     public static function validateAddress($address, $patternselect = 'auto')
     {
-        if ($patternselect == 'auto') {
-            if (defined(
-                'PCRE_VERSION'
-            )
-            ) { //Check this instead of extension_loaded so it works when that function is disabled
+        if (!$patternselect or $patternselect == 'auto') {
+            if (defined('PCRE_VERSION')) { //Check this constant so it works when extension_loaded() is disabled
                 if (version_compare(PCRE_VERSION, '8.0') >= 0) {
                     $patternselect = 'pcre8';
                 } else {
@@ -858,9 +867,7 @@ class PHPMailer
         switch ($patternselect) {
             case 'pcre8':
                 /**
-                 * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
-                 * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
-                 * not allow a@b type valid addresses :(
+                 * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
                  * @link http://squiloople.com/2009/12/20/email-address-validation/
                  * @copyright 2009-2010 Michael Rushton
                  * Feel free to use and redistribute this code. But please keep this copyright notice.
@@ -894,6 +901,14 @@ class PHPMailer
                     $address
                 );
                 break;
+            case 'html5':
+                /**
+                 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
+                 * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
+                 */
+                return (bool)preg_match('/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
+                    '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', $address);
+                break;
             case 'php':
             default:
                 return (bool)filter_var($address, FILTER_VALIDATE_EMAIL);
@@ -911,9 +926,8 @@ class PHPMailer
     /**
      * Create a message and send it.
      * Uses the sending method specified by $Mailer.
-     * Returns false on error - Use the ErrorInfo variable to view description of the error.
      * @throws phpmailerException
-     * @return bool
+     * @return bool false on error - See the ErrorInfo property for details of the error.
      */
     public function send()
     {
@@ -922,11 +936,11 @@ class PHPMailer
                 return false;
             }
             return $this->postSend();
-        } catch (phpmailerException $e) {
+        } catch (phpmailerException $exc) {
             $this->mailHeader = '';
-            $this->setError($e->getMessage());
+            $this->setError($exc->getMessage());
             if ($this->exceptions) {
-                throw $e;
+                throw $exc;
             }
             return false;
         }
@@ -940,7 +954,7 @@ class PHPMailer
     public function preSend()
     {
         try {
-            $this->mailHeader = "";
+            $this->mailHeader = '';
             if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
                 throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
             }
@@ -964,9 +978,9 @@ class PHPMailer
             // an extra header list which createHeader() doesn't fold in
             if ($this->Mailer == 'mail') {
                 if (count($this->to) > 0) {
-                    $this->mailHeader .= $this->addrAppend("To", $this->to);
+                    $this->mailHeader .= $this->addrAppend('To', $this->to);
                 } else {
-                    $this->mailHeader .= $this->headerLine("To", "undisclosed-recipients:;");
+                    $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
                 }
                 $this->mailHeader .= $this->headerLine(
                     'Subject',
@@ -990,10 +1004,10 @@ class PHPMailer
             }
             return true;
 
-        } catch (phpmailerException $e) {
-            $this->setError($e->getMessage());
+        } catch (phpmailerException $exc) {
+            $this->setError($exc->getMessage());
             if ($this->exceptions) {
-                throw $e;
+                throw $exc;
             }
             return false;
         }
@@ -1011,20 +1025,26 @@ class PHPMailer
             // Choose the mailer and send through it
             switch ($this->Mailer) {
                 case 'sendmail':
+                case 'qmail':
                     return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
                 case 'smtp':
                     return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
                 case 'mail':
                     return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
                 default:
+                    $sendMethod = $this->Mailer.'Send';
+                    if (method_exists($this, $sendMethod)) {
+                        return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
+                    }
+                    
                     return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
             }
-        } catch (phpmailerException $e) {
-            $this->setError($e->getMessage());
+        } catch (phpmailerException $exc) {
+            $this->setError($exc->getMessage());
+            $this->edebug($exc->getMessage());
             if ($this->exceptions) {
-                throw $e;
+                throw $exc;
             }
-            $this->edebug($e->getMessage() . "\n");
         }
         return false;
     }
@@ -1041,16 +1061,24 @@ class PHPMailer
     protected function sendmailSend($header, $body)
     {
         if ($this->Sender != '') {
-            $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
+            if ($this->Mailer == 'qmail') {
+                $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
+            } else {
+                $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
+            }
         } else {
-            $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
+            if ($this->Mailer == 'qmail') {
+                $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
+            } else {
+                $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
+            }
         }
         if ($this->SingleTo === true) {
             foreach ($this->SingleToArray as $val) {
                 if (!@$mail = popen($sendmail, 'w')) {
                     throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
                 }
-                fputs($mail, "To: " . $val . "\n");
+                fputs($mail, 'To: ' . $val . "\n");
                 fputs($mail, $header);
                 fputs($mail, $body);
                 $result = pclose($mail);
@@ -1090,38 +1118,38 @@ class PHPMailer
     protected function mailSend($header, $body)
     {
         $toArr = array();
-        foreach ($this->to as $t) {
-            $toArr[] = $this->addrFormat($t);
+        foreach ($this->to as $toaddr) {
+            $toArr[] = $this->addrFormat($toaddr);
         }
         $to = implode(', ', $toArr);
 
         if (empty($this->Sender)) {
-            $params = " ";
+            $params = ' ';
         } else {
-            $params = sprintf("-f%s", $this->Sender);
+            $params = sprintf('-f%s', $this->Sender);
         }
         if ($this->Sender != '' and !ini_get('safe_mode')) {
             $old_from = ini_get('sendmail_from');
             ini_set('sendmail_from', $this->Sender);
         }
-        $rt = false;
+        $result = false;
         if ($this->SingleTo === true && count($toArr) > 1) {
             foreach ($toArr as $val) {
-                $rt = $this->mailPassthru($val, $this->Subject, $body, $header, $params);
+                $result = $this->mailPassthru($val, $this->Subject, $body, $header, $params);
                 // implement call back function if it exists
-                $isSent = ($rt == 1) ? 1 : 0;
+                $isSent = ($result == 1) ? 1 : 0;
                 $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
             }
         } else {
-            $rt = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
+            $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
             // implement call back function if it exists
-            $isSent = ($rt == 1) ? 1 : 0;
+            $isSent = ($result == 1) ? 1 : 0;
             $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
         }
         if (isset($old_from)) {
             ini_set('sendmail_from', $old_from);
         }
-        if (!$rt) {
+        if (!$result) {
             throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
         }
         return true;
@@ -1135,7 +1163,7 @@ class PHPMailer
     public function getSMTPInstance()
     {
         if (!is_object($this->smtp)) {
-            require_once 'class-smtp.php';
+			require_once 'class-smtp.php';
             $this->smtp = new SMTP;
         }
         return $this->smtp;
@@ -1166,7 +1194,7 @@ class PHPMailer
             throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
         }
 
-        // Attempt to send attach all recipients
+        // Attempt to send to all recipients
         foreach ($this->to as $to) {
             if (!$this->smtp->recipient($to[0])) {
                 $bad_rcpt[] = $to[0];
@@ -1195,10 +1223,8 @@ class PHPMailer
             $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body, $this->From);
         }
 
-        if (count($bad_rcpt) > 0) { //Create error message for any bad addresses
-            throw new phpmailerException($this->lang('recipients_failed') . implode(', ', $bad_rcpt));
-        }
-        if (!$this->smtp->data($header . $body)) {
+        //Only send the DATA command if we have viable recipients
+        if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
             throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
         }
         if ($this->SMTPKeepAlive == true) {
@@ -1207,6 +1233,12 @@ class PHPMailer
             $this->smtp->quit();
             $this->smtp->close();
         }
+        if (count($bad_rcpt) > 0) { //Create error message for any bad addresses
+            throw new phpmailerException(
+                $this->lang('recipients_failed') . implode(', ', $bad_rcpt),
+                self::STOP_CONTINUE
+            );
+        }
         return true;
     }
 
@@ -1234,25 +1266,36 @@ class PHPMailer
         $this->smtp->setDebugLevel($this->SMTPDebug);
         $this->smtp->setDebugOutput($this->Debugoutput);
         $this->smtp->setVerp($this->do_verp);
-        $tls = ($this->SMTPSecure == 'tls');
-        $ssl = ($this->SMTPSecure == 'ssl');
         $hosts = explode(';', $this->Host);
         $lastexception = null;
 
         foreach ($hosts as $hostentry) {
             $hostinfo = array();
-            $host = $hostentry;
+            if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
+                //Not a valid host entry
+                continue;
+            }
+            //$hostinfo[2]: optional ssl or tls prefix
+            //$hostinfo[3]: the hostname
+            //$hostinfo[4]: optional port number
+            //The host string prefix can temporarily override the current setting for SMTPSecure
+            //If it's not specified, the default value is used
+            $prefix = '';
+            $tls = ($this->SMTPSecure == 'tls');
+            if ($hostinfo[2] == 'ssl' or ($hostinfo[2] == '' and $this->SMTPSecure == 'ssl')) {
+                $prefix = 'ssl://';
+                $tls = false; //Can't have SSL and TLS at once
+            } elseif ($hostinfo[2] == 'tls') {
+                $tls = true;
+                //tls doesn't use a prefix
+            }
+            $host = $hostinfo[3];
             $port = $this->Port;
-            if (preg_match(
-                '/^(.+):([0-9]+)$/',
-                $hostentry,
-                $hostinfo
-            )
-            ) { //If $hostentry contains 'address:port', override default
-                $host = $hostinfo[1];
-                $port = $hostinfo[2];
+            $tport = (integer)$hostinfo[4];
+            if ($tport > 0 and $tport < 65536) {
+                $port = $tport;
             }
-            if ($this->smtp->connect(($ssl ? 'ssl://' : '') . $host, $port, $this->Timeout, $options)) {
+            if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
                 try {
                     if ($this->Helo) {
                         $hello = $this->Helo;
@@ -1281,8 +1324,8 @@ class PHPMailer
                         }
                     }
                     return true;
-                } catch (phpmailerException $e) {
-                    $lastexception = $e;
+                } catch (phpmailerException $exc) {
+                    $lastexception = $exc;
                     //We must have connected, but then failed TLS or Auth, so close connection nicely
                     $this->smtp->quit();
                 }
@@ -1320,9 +1363,9 @@ class PHPMailer
      * @return bool
      * @access public
      */
-    public function setLanguage($langcode = 'en', $lang_path = 'language/')
+    public function setLanguage($langcode = 'en', $lang_path = '')
     {
-        //Define full set of translatable strings
+        //Define full set of translatable strings in English
         $PHPMAILER_LANG = array(
             'authenticate' => 'SMTP Error: Could not authenticate.',
             'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
@@ -1343,14 +1386,24 @@ class PHPMailer
             'smtp_error' => 'SMTP server error: ',
             'variable_set' => 'Cannot set or reset variable: '
         );
-        //Overwrite language-specific strings.
-        //This way we'll never have missing translations - no more "language string failed to load"!
-        $l = true;
+        if (empty($lang_path)) {
+            //Calculate an absolute path so it can work if CWD is not here
+            $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
+        }
+        $foundlang = true;
+        $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
         if ($langcode != 'en') { //There is no English translation file
-            $l = @include $lang_path . 'phpmailer.lang-' . $langcode . '.php';
+            //Make sure language file path is readable
+            if (!is_readable($lang_file)) {
+                $foundlang = false;
+            } else {
+                //Overwrite language-specific strings.
+                //This way we'll never have missing translations.
+                $foundlang = include $lang_file;
+            }
         }
         $this->language = $PHPMAILER_LANG;
-        return ($l == true); //Returns false if language not found
+        return ($foundlang == true); //Returns false if language not found
     }
 
     /**
@@ -1375,8 +1428,8 @@ class PHPMailer
     public function addrAppend($type, $addr)
     {
         $addresses = array();
-        foreach ($addr as $a) {
-            $addresses[] = $this->addrFormat($a);
+        foreach ($addr as $address) {
+            $addresses[] = $this->addrFormat($address);
         }
         return $type . ': ' . implode(', ', $addresses) . $this->LE;
     }
@@ -1393,9 +1446,9 @@ class PHPMailer
         if (empty($addr[1])) { // No name provided
             return $this->secureHeader($addr[0]);
         } else {
-            return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . " <" . $this->secureHeader(
+            return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
                 $addr[0]
-            ) . ">";
+            ) . '>';
         }
     }
 
@@ -1412,10 +1465,10 @@ class PHPMailer
      */
     public function wrapText($message, $length, $qp_mode = false)
     {
-        $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
+        $soft_break = ($qp_mode) ? sprintf(' =%s', $this->LE) : $this->LE;
         // If utf-8 encoding is used, we will need to make sure we don't
         // split multibyte characters when we wrap
-        $is_utf8 = (strtolower($this->CharSet) == "utf-8");
+        $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
         $lelen = strlen($this->LE);
         $crlflen = strlen(self::CRLF);
 
@@ -1438,15 +1491,15 @@ class PHPMailer
                             $len = $space_left;
                             if ($is_utf8) {
                                 $len = $this->utf8CharBoundary($word, $len);
-                            } elseif (substr($word, $len - 1, 1) == "=") {
+                            } elseif (substr($word, $len - 1, 1) == '=') {
                                 $len--;
-                            } elseif (substr($word, $len - 2, 1) == "=") {
+                            } elseif (substr($word, $len - 2, 1) == '=') {
                                 $len -= 2;
                             }
                             $part = substr($word, 0, $len);
                             $word = substr($word, $len);
                             $buf .= ' ' . $part;
-                            $message .= $buf . sprintf("=%s", self::CRLF);
+                            $message .= $buf . sprintf('=%s', self::CRLF);
                         } else {
                             $message .= $buf . $soft_break;
                         }
@@ -1459,16 +1512,16 @@ class PHPMailer
                         $len = $length;
                         if ($is_utf8) {
                             $len = $this->utf8CharBoundary($word, $len);
-                        } elseif (substr($word, $len - 1, 1) == "=") {
+                        } elseif (substr($word, $len - 1, 1) == '=') {
                             $len--;
-                        } elseif (substr($word, $len - 2, 1) == "=") {
+                        } elseif (substr($word, $len - 2, 1) == '=') {
                             $len -= 2;
                         }
                         $part = substr($word, 0, $len);
                         $word = substr($word, $len);
 
                         if (strlen($word) > 0) {
-                            $message .= $part . sprintf("=%s", self::CRLF);
+                            $message .= $part . sprintf('=%s', self::CRLF);
                         } else {
                             $buf = $part;
                         }
@@ -1504,7 +1557,7 @@ class PHPMailer
         $lookBack = 3;
         while (!$foundSplitPos) {
             $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
-            $encodedCharPos = strpos($lastChunk, "=");
+            $encodedCharPos = strpos($lastChunk, '=');
             if ($encodedCharPos !== false) {
                 // Found start of encoded character byte within $lookBack block.
                 // Check the encoded byte value (the 2 chars after the '=')
@@ -1531,7 +1584,6 @@ class PHPMailer
         return $maxLength;
     }
 
-
     /**
      * Set the body wrapping.
      * @access public
@@ -1572,31 +1624,25 @@ class PHPMailer
         $this->boundary[3] = 'b3_' . $uniq_id;
 
         if ($this->MessageDate == '') {
-            $result .= $this->headerLine('Date', self::rfcDate());
-        } else {
-            $result .= $this->headerLine('Date', $this->MessageDate);
+            $this->MessageDate = self::rfcDate();
         }
+        $result .= $this->headerLine('Date', $this->MessageDate);
 
-        if ($this->ReturnPath) {
-            $result .= $this->headerLine('Return-Path', '<' . trim($this->ReturnPath) . '>');
-        } elseif ($this->Sender == '') {
-            $result .= $this->headerLine('Return-Path', '<' . trim($this->From) . '>');
-        } else {
-            $result .= $this->headerLine('Return-Path', '<' . trim($this->Sender) . '>');
-        }
 
         // To be created automatically by mail()
-        if ($this->Mailer != 'mail') {
-            if ($this->SingleTo === true) {
-                foreach ($this->to as $t) {
-                    $this->SingleToArray[] = $this->addrFormat($t);
+        if ($this->SingleTo === true) {
+            if ($this->Mailer != 'mail') {
+                foreach ($this->to as $toaddr) {
+                    $this->SingleToArray[] = $this->addrFormat($toaddr);
                 }
-            } else {
-                if (count($this->to) > 0) {
+            }
+        } else {
+            if (count($this->to) > 0) {
+                if ($this->Mailer != 'mail') {
                     $result .= $this->addrAppend('To', $this->to);
-                } elseif (count($this->cc) == 0) {
-                    $result .= $this->headerLine('To', 'undisclosed-recipients:;');
                 }
+            } elseif (count($this->cc) == 0) {
+                $result .= $this->headerLine('To', 'undisclosed-recipients:;');
             }
         }
 
@@ -1608,7 +1654,11 @@ class PHPMailer
         }
 
         // sendmail and mail() extract Bcc from the header before sending
-        if ((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
+        if ((
+                $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
+            )
+            and count($this->bcc) > 0
+        ) {
             $result .= $this->addrAppend('Bcc', $this->bcc);
         }
 
@@ -1624,7 +1674,7 @@ class PHPMailer
         if ($this->MessageID != '') {
             $this->lastMessageID = $this->MessageID;
         } else {
-            $this->lastMessageID = sprintf("<%s@%s>", $uniq_id, $this->ServerHostname());
+            $this->lastMessageID = sprintf('<%s@%s>', $uniq_id, $this->ServerHostname());
         }
         $result .= $this->HeaderLine('Message-ID', $this->lastMessageID);
         $result .= $this->headerLine('X-Priority', $this->Priority);
@@ -1667,6 +1717,7 @@ class PHPMailer
     public function getMailMIME()
     {
         $result = '';
+        $ismultipart = true;
         switch ($this->message_type) {
             case 'inline':
                 $result .= $this->headerLine('Content-Type', 'multipart/related;');
@@ -1687,11 +1738,20 @@ class PHPMailer
             default:
                 // Catches case 'plain': and case '':
                 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
+                $ismultipart = false;
                 break;
         }
         //RFC1341 part 5 says 7bit is assumed if not specified
         if ($this->Encoding != '7bit') {
-            $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
+            //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
+            if ($ismultipart) {
+                if ($this->Encoding == '8bit') {
+                    $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
+                }
+                //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
+            } else {
+                $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
+            }
         }
 
         if ($this->Mailer != 'mail') {
@@ -1704,8 +1764,8 @@ class PHPMailer
     /**
      * Returns the whole MIME message.
      * Includes complete headers and body.
-     * Only valid post PreSend().
-     * @see PHPMailer::PreSend()
+     * Only valid post preSend().
+     * @see PHPMailer::preSend()
      * @access public
      * @return string
      */
@@ -1732,16 +1792,28 @@ class PHPMailer
 
         $this->setWordWrap();
 
+        $bodyEncoding = $this->Encoding;
+        $bodyCharSet = $this->CharSet;
+        if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
+            $bodyEncoding = '7bit';
+            $bodyCharSet = 'us-ascii';
+        }
+        $altBodyEncoding = $this->Encoding;
+        $altBodyCharSet = $this->CharSet;
+        if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
+            $altBodyEncoding = '7bit';
+            $altBodyCharSet = 'us-ascii';
+        }
         switch ($this->message_type) {
             case 'inline':
-                $body .= $this->getBoundary($this->boundary[1], '', '', '');
-                $body .= $this->encodeString($this->Body, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
+                $body .= $this->encodeString($this->Body, $bodyEncoding);
                 $body .= $this->LE . $this->LE;
                 $body .= $this->attachAll('inline', $this->boundary[1]);
                 break;
             case 'attach':
-                $body .= $this->getBoundary($this->boundary[1], '', '', '');
-                $body .= $this->encodeString($this->Body, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
+                $body .= $this->encodeString($this->Body, $bodyEncoding);
                 $body .= $this->LE . $this->LE;
                 $body .= $this->attachAll('attachment', $this->boundary[1]);
                 break;
@@ -1750,19 +1822,19 @@ class PHPMailer
                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
                 $body .= $this->LE;
-                $body .= $this->getBoundary($this->boundary[2], '', '', '');
-                $body .= $this->encodeString($this->Body, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
+                $body .= $this->encodeString($this->Body, $bodyEncoding);
                 $body .= $this->LE . $this->LE;
                 $body .= $this->attachAll('inline', $this->boundary[2]);
                 $body .= $this->LE;
                 $body .= $this->attachAll('attachment', $this->boundary[1]);
                 break;
             case 'alt':
-                $body .= $this->getBoundary($this->boundary[1], '', 'text/plain', '');
-                $body .= $this->encodeString($this->AltBody, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
+                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
                 $body .= $this->LE . $this->LE;
-                $body .= $this->getBoundary($this->boundary[1], '', 'text/html', '');
-                $body .= $this->encodeString($this->Body, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
+                $body .= $this->encodeString($this->Body, $bodyEncoding);
                 $body .= $this->LE . $this->LE;
                 if (!empty($this->Ical)) {
                     $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
@@ -1772,15 +1844,15 @@ class PHPMailer
                 $body .= $this->endBoundary($this->boundary[1]);
                 break;
             case 'alt_inline':
-                $body .= $this->getBoundary($this->boundary[1], '', 'text/plain', '');
-                $body .= $this->encodeString($this->AltBody, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
+                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
                 $body .= $this->LE . $this->LE;
                 $body .= $this->textLine('--' . $this->boundary[1]);
                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
                 $body .= $this->LE;
-                $body .= $this->getBoundary($this->boundary[2], '', 'text/html', '');
-                $body .= $this->encodeString($this->Body, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
+                $body .= $this->encodeString($this->Body, $bodyEncoding);
                 $body .= $this->LE . $this->LE;
                 $body .= $this->attachAll('inline', $this->boundary[2]);
                 $body .= $this->LE;
@@ -1791,11 +1863,11 @@ class PHPMailer
                 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
                 $body .= $this->LE;
-                $body .= $this->getBoundary($this->boundary[2], '', 'text/plain', '');
-                $body .= $this->encodeString($this->AltBody, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
+                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
                 $body .= $this->LE . $this->LE;
-                $body .= $this->getBoundary($this->boundary[2], '', 'text/html', '');
-                $body .= $this->encodeString($this->Body, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
+                $body .= $this->encodeString($this->Body, $bodyEncoding);
                 $body .= $this->LE . $this->LE;
                 $body .= $this->endBoundary($this->boundary[2]);
                 $body .= $this->LE;
@@ -1806,15 +1878,15 @@ class PHPMailer
                 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
                 $body .= $this->LE;
-                $body .= $this->getBoundary($this->boundary[2], '', 'text/plain', '');
-                $body .= $this->encodeString($this->AltBody, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
+                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
                 $body .= $this->LE . $this->LE;
                 $body .= $this->textLine('--' . $this->boundary[2]);
                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
                 $body .= $this->LE;
-                $body .= $this->getBoundary($this->boundary[3], '', 'text/html', '');
-                $body .= $this->encodeString($this->Body, $this->Encoding);
+                $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
+                $body .= $this->encodeString($this->Body, $bodyEncoding);
                 $body .= $this->LE . $this->LE;
                 $body .= $this->attachAll('inline', $this->boundary[3]);
                 $body .= $this->LE;
@@ -1824,7 +1896,7 @@ class PHPMailer
                 break;
             default:
                 // catch case 'plain' and case ''
-                $body .= $this->encodeString($this->Body, $this->Encoding);
+                $body .= $this->encodeString($this->Body, $bodyEncoding);
                 break;
         }
 
@@ -1835,6 +1907,7 @@ class PHPMailer
                 if (!defined('PKCS7_TEXT')) {
                     throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
                 }
+                //TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
                 $file = tempnam(sys_get_temp_dir(), 'mail');
                 file_put_contents($file, $body); //TODO check this worked
                 $signed = tempnam(sys_get_temp_dir(), 'signed');
@@ -1854,10 +1927,10 @@ class PHPMailer
                     @unlink($signed);
                     throw new phpmailerException($this->lang('signing') . openssl_error_string());
                 }
-            } catch (phpmailerException $e) {
+            } catch (phpmailerException $exc) {
                 $body = '';
                 if ($this->exceptions) {
-                    throw $e;
+                    throw $exc;
                 }
             }
         }
@@ -1886,9 +1959,12 @@ class PHPMailer
             $encoding = $this->Encoding;
         }
         $result .= $this->textLine('--' . $boundary);
-        $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
+        $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
         $result .= $this->LE;
-        $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
+        //RFC1341 part 5 says 7bit is assumed if not specified
+        if ($encoding != '7bit') {
+            $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
+        }
         $result .= $this->LE;
 
         return $result;
@@ -1916,17 +1992,17 @@ class PHPMailer
     {
         $this->message_type = array();
         if ($this->alternativeExists()) {
-            $this->message_type[] = "alt";
+            $this->message_type[] = 'alt';
         }
         if ($this->inlineImageExists()) {
-            $this->message_type[] = "inline";
+            $this->message_type[] = 'inline';
         }
         if ($this->attachmentExists()) {
-            $this->message_type[] = "attach";
+            $this->message_type[] = 'attach';
         }
-        $this->message_type = implode("_", $this->message_type);
-        if ($this->message_type == "") {
-            $this->message_type = "plain";
+        $this->message_type = implode('_', $this->message_type);
+        if ($this->message_type == '') {
+            $this->message_type = 'plain';
         }
     }
 
@@ -1992,12 +2068,12 @@ class PHPMailer
                 7 => 0
             );
 
-        } catch (phpmailerException $e) {
-            $this->setError($e->getMessage());
+        } catch (phpmailerException $exc) {
+            $this->setError($exc->getMessage());
+            $this->edebug($exc->getMessage());
             if ($this->exceptions) {
-                throw $e;
+                throw $exc;
             }
-            $this->edebug($e->getMessage() . "\n");
             return false;
         }
         return true;
@@ -2056,17 +2132,20 @@ class PHPMailer
                 }
                 $cidUniq[$cid] = true;
 
-                $mime[] = sprintf("--%s%s", $boundary, $this->LE);
+                $mime[] = sprintf('--%s%s', $boundary, $this->LE);
                 $mime[] = sprintf(
-                    "Content-Type: %s; name=\"%s\"%s",
+                    'Content-Type: %s; name="%s"%s',
                     $type,
                     $this->encodeHeader($this->secureHeader($name)),
                     $this->LE
                 );
-                $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
+                //RFC1341 part 5 says 7bit is assumed if not specified
+                if ($encoding != '7bit') {
+                    $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
+                }
 
                 if ($disposition == 'inline') {
-                    $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
+                    $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
                 }
 
                 // If a filename contains any of these chars, it should be quoted,
@@ -2076,14 +2155,14 @@ class PHPMailer
                 if (!(empty($disposition))) {
                     if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) {
                         $mime[] = sprintf(
-                            "Content-Disposition: %s; filename=\"%s\"%s",
+                            'Content-Disposition: %s; filename="%s"%s',
                             $disposition,
                             $this->encodeHeader($this->secureHeader($name)),
                             $this->LE . $this->LE
                         );
                     } else {
                         $mime[] = sprintf(
-                            "Content-Disposition: %s; filename=%s%s",
+                            'Content-Disposition: %s; filename=%s%s',
                             $disposition,
                             $this->encodeHeader($this->secureHeader($name)),
                             $this->LE . $this->LE
@@ -2110,9 +2189,9 @@ class PHPMailer
             }
         }
 
-        $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
+        $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
 
-        return implode("", $mime);
+        return implode('', $mime);
     }
 
     /**
@@ -2149,8 +2228,8 @@ class PHPMailer
                 }
             }
             return $file_buffer;
-        } catch (Exception $e) {
-            $this->setError($e->getMessage());
+        } catch (Exception $exc) {
+            $this->setError($exc->getMessage());
             return '';
         }
     }
@@ -2201,11 +2280,11 @@ class PHPMailer
      */
     public function encodeHeader($str, $position = 'text')
     {
-        $x = 0;
+        $matchcount = 0;
         switch (strtolower($position)) {
             case 'phrase':
                 if (!preg_match('/[\200-\377]/', $str)) {
-                    // Can't use addslashes as we don't know what value has magic_quotes_sybase
+                    // Can't use addslashes as we don't know the value of magic_quotes_sybase
                     $encoded = addcslashes($str, "\0..\37\177\\\"");
                     if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
                         return ($encoded);
@@ -2213,25 +2292,25 @@ class PHPMailer
                         return ("\"$encoded\"");
                     }
                 }
-                $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
+                $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
                 break;
             /** @noinspection PhpMissingBreakStatementInspection */
             case 'comment':
-                $x = preg_match_all('/[()"]/', $str, $matches);
+                $matchcount = preg_match_all('/[()"]/', $str, $matches);
                 // Intentional fall-through
             case 'text':
             default:
-                $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
+                $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
                 break;
         }
 
-        if ($x == 0) { //There are no chars that need encoding
+        if ($matchcount == 0) { //There are no chars that need encoding
             return ($str);
         }
 
         $maxlen = 75 - 7 - strlen($this->CharSet);
         // Try to select the encoding which should produce the shortest output
-        if ($x > strlen($str) / 3) {
+        if ($matchcount > strlen($str) / 3) {
             //More than a third of the content will need encoding, so B encoding will be most efficient
             $encoding = 'B';
             if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
@@ -2250,7 +2329,7 @@ class PHPMailer
             $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
         }
 
-        $encoded = preg_replace('/^(.*)$/m', " =?" . $this->CharSet . "?$encoding?\\1?=", $encoded);
+        $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
         $encoded = trim(str_replace("\n", $this->LE, $encoded));
 
         return $encoded;
@@ -2272,21 +2351,32 @@ class PHPMailer
     }
 
     /**
+     * Does a string contain any 8-bit chars (in any charset)?
+     * @param string $text
+     * @return bool
+     */
+    public function has8bitChars($text)
+    {
+        return (bool)preg_match('/[\x80-\xFF]/', $text);
+    }
+
+    /**
      * Encode and wrap long multibyte strings for mail headers
      * without breaking lines within a character.
-     * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
+     * Adapted from a function by paravoid
+     * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
      * @access public
      * @param string $str multi-byte text to wrap encode
-     * @param string $lf string to use as linefeed/end-of-line
+     * @param string $linebreak string to use as linefeed/end-of-line
      * @return string
      */
-    public function base64EncodeWrapMB($str, $lf = null)
+    public function base64EncodeWrapMB($str, $linebreak = null)
     {
-        $start = "=?" . $this->CharSet . "?B?";
-        $end = "?=";
-        $encoded = "";
-        if ($lf === null) {
-            $lf = $this->LE;
+        $start = '=?' . $this->CharSet . '?B?';
+        $end = '?=';
+        $encoded = '';
+        if ($linebreak === null) {
+            $linebreak = $this->LE;
         }
 
         $mb_length = mb_strlen($str, $this->CharSet);
@@ -2305,11 +2395,11 @@ class PHPMailer
                 $chunk = base64_encode($chunk);
                 $lookBack++;
             } while (strlen($chunk) > $length);
-            $encoded .= $chunk . $lf;
+            $encoded .= $chunk . $linebreak;
         }
 
         // Chomp the last linefeed
-        $encoded = substr($encoded, 0, -strlen($lf));
+        $encoded = substr($encoded, 0, -strlen($linebreak));
         return $encoded;
     }
 
@@ -2320,12 +2410,12 @@ class PHPMailer
      * @param string $string The text to encode
      * @param integer $line_max Number of chars allowed on a line before wrapping
      * @return string
-     * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417
+     * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
      */
     public function encodeQP($string, $line_max = 76)
     {
         if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
-            return quoted_printable_encode($string);
+            return $this->fixEOL(quoted_printable_encode($string));
         }
         //Fall back to a pure PHP implementation
         $string = str_replace(
@@ -2334,7 +2424,7 @@ class PHPMailer
             rawurlencode($string)
         );
         $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
-        return $string;
+        return $this->fixEOL($string);
     }
 
     /**
@@ -2390,9 +2480,9 @@ class PHPMailer
         if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
             //If the string contains an '=', make sure it's the first thing we replace
             //so as to avoid double-encoding
-            $s = array_search('=', $matches[0]);
-            if ($s !== false) {
-                unset($matches[0][$s]);
+            $eqkey = array_search('=', $matches[0]);
+            if ($eqkey !== false) {
+                unset($matches[0][$eqkey]);
                 array_unshift($matches[0], '=');
             }
             foreach (array_unique($matches[0]) as $char) {
@@ -2680,14 +2770,16 @@ class PHPMailer
      */
     protected function serverHostname()
     {
+        $result = 'localhost.localdomain';
         if (!empty($this->Hostname)) {
             $result = $this->Hostname;
-        } elseif (isset($_SERVER['SERVER_NAME'])) {
+        } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
             $result = $_SERVER['SERVER_NAME'];
-        } else {
-            $result = 'localhost.localdomain';
+        } elseif (function_exists('gethostname') && gethostname() !== false) {
+            $result = gethostname();
+        } elseif (php_uname('n') !== false) {
+            $result = php_uname('n');
         }
-
         return $result;
     }
 
@@ -2770,9 +2862,9 @@ class PHPMailer
      */
     public function msgHTML($message, $basedir = '', $advanced = false)
     {
-        preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
+        preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
         if (isset($images[2])) {
-            foreach ($images[2] as $i => $url) {
+            foreach ($images[2] as $imgindex => $url) {
                 // do not change urls for absolute images (thanks to corvuscorax)
                 if (!preg_match('#^[A-z]+://#', $url)) {
                     $filename = basename($url);
@@ -2796,8 +2888,8 @@ class PHPMailer
                     )
                     ) {
                         $message = preg_replace(
-                            "/" . $images[1][$i] . "=[\"']" . preg_quote($url, '/') . "[\"']/Ui",
-                            $images[1][$i] . "=\"cid:" . $cid . "\"",
+                            '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
+                            $images[1][$imgindex] . '="cid:' . $cid . '"',
                             $message
                         );
                     }
@@ -2805,12 +2897,13 @@ class PHPMailer
             }
         }
         $this->isHTML(true);
-        if (empty($this->AltBody)) {
-            $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
-        }
         //Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
         $this->Body = $this->normalizeBreaks($message);
         $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
+        if (empty($this->AltBody)) {
+            $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
+                self::CRLF . self::CRLF;
+        }
         return $this->Body;
     }
 
@@ -2824,8 +2917,8 @@ class PHPMailer
     {
         if ($advanced) {
             require_once 'extras/class.html2text.php';
-            $h = new html2text($html);
-            return $h->get_text();
+            $htmlconverter = new html2text($html);
+            return $htmlconverter->get_text();
         }
         return html_entity_decode(
             trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
@@ -2920,6 +3013,8 @@ class PHPMailer
             'txt' => 'text/plain',
             'rtx' => 'text/richtext',
             'rtf' => 'text/rtf',
+            'vcf' => 'text/vcard',
+            'vcard' => 'text/vcard',
             'xml' => 'text/xml',
             'xsl' => 'text/xml',
             'mpeg' => 'video/mpeg',
@@ -2966,19 +3061,19 @@ class PHPMailer
     public static function mb_pathinfo($path, $options = null)
     {
         $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
-        $m = array();
-        preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m);
-        if (array_key_exists(1, $m)) {
-            $ret['dirname'] = $m[1];
+        $pathinfo = array();
+        preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo);
+        if (array_key_exists(1, $pathinfo)) {
+            $ret['dirname'] = $pathinfo[1];
         }
-        if (array_key_exists(2, $m)) {
-            $ret['basename'] = $m[2];
+        if (array_key_exists(2, $pathinfo)) {
+            $ret['basename'] = $pathinfo[2];
         }
-        if (array_key_exists(5, $m)) {
-            $ret['extension'] = $m[5];
+        if (array_key_exists(5, $pathinfo)) {
+            $ret['extension'] = $pathinfo[5];
         }
-        if (array_key_exists(3, $m)) {
-            $ret['filename'] = $m[3];
+        if (array_key_exists(3, $pathinfo)) {
+            $ret['filename'] = $pathinfo[3];
         }
         switch ($options) {
             case PATHINFO_DIRNAME:
@@ -3024,9 +3119,9 @@ class PHPMailer
             } else {
                 throw new phpmailerException($this->lang('variable_set') . $name, self::STOP_CRITICAL);
             }
-        } catch (Exception $e) {
-            $this->setError($e->getMessage());
-            if ($e->getCode() == self::STOP_CRITICAL) {
+        } catch (Exception $exc) {
+            $this->setError($exc->getMessage());
+            if ($exc->getCode() == self::STOP_CRITICAL) {
                 return false;
             }
         }
@@ -3061,7 +3156,7 @@ class PHPMailer
 
 
     /**
-     * Set the private key file and password for S/MIME signing.
+     * Set the public and private key files and password for S/MIME signing.
      * @access public
      * @param string $cert_filename
      * @param string $key_filename
@@ -3088,7 +3183,7 @@ class PHPMailer
             if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
                 $line .= $txt[$i];
             } else {
-                $line .= "=" . sprintf("%02X", $ord);
+                $line .= '=' . sprintf('%02X', $ord);
             }
         }
         return $line;
@@ -3097,15 +3192,15 @@ class PHPMailer
     /**
      * Generate a DKIM signature.
      * @access public
-     * @param string $s Header
+     * @param string $signheader Header
      * @throws phpmailerException
      * @return string
      */
-    public function DKIM_Sign($s)
+    public function DKIM_Sign($signheader)
     {
         if (!defined('PKCS7_TEXT')) {
             if ($this->exceptions) {
-                throw new phpmailerException($this->lang("signing") . ' OpenSSL extension missing.');
+                throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
             }
             return '';
         }
@@ -3115,7 +3210,7 @@ class PHPMailer
         } else {
             $privKey = $privKeyStr;
         }
-        if (openssl_sign($s, $signature, $privKey)) {
+        if (openssl_sign($signheader, $signature, $privKey)) {
             return base64_encode($signature);
         }
         return '';
@@ -3124,21 +3219,21 @@ class PHPMailer
     /**
      * Generate a DKIM canonicalization header.
      * @access public
-     * @param string $s Header
+     * @param string $signheader Header
      * @return string
      */
-    public function DKIM_HeaderC($s)
+    public function DKIM_HeaderC($signheader)
     {
-        $s = preg_replace("/\r\n\s+/", " ", $s);
-        $lines = explode("\r\n", $s);
+        $signheader = preg_replace('/\r\n\s+/', ' ', $signheader);
+        $lines = explode("\r\n", $signheader);
         foreach ($lines as $key => $line) {
-            list($heading, $value) = explode(":", $line, 2);
+            list($heading, $value) = explode(':', $line, 2);
             $heading = strtolower($heading);
-            $value = preg_replace("/\s+/", " ", $value); // Compress useless spaces
-            $lines[$key] = $heading . ":" . trim($value); // Don't forget to remove WSP around the value
+            $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
+            $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
         }
-        $s = implode("\r\n", $lines);
-        return $s;
+        $signheader = implode("\r\n", $lines);
+        return $signheader;
     }
 
     /**
@@ -3205,17 +3300,17 @@ class PHPMailer
         ); // Copied header fields (dkim-quoted-printable)
         $body = $this->DKIM_BodyC($body);
         $DKIMlen = strlen($body); // Length of body
-        $DKIMb64 = base64_encode(pack("H*", sha1($body))); // Base64 of packed binary SHA-1 hash of body
-        $ident = ($this->DKIM_identity == '') ? '' : " i=" . $this->DKIM_identity . ";";
-        $dkimhdrs = "DKIM-Signature: v=1; a=" .
-            $DKIMsignatureType . "; q=" .
-            $DKIMquery . "; l=" .
-            $DKIMlen . "; s=" .
+        $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
+        $ident = ($this->DKIM_identity == '') ? '' : ' i=' . $this->DKIM_identity . ';';
+        $dkimhdrs = 'DKIM-Signature: v=1; a=' .
+            $DKIMsignatureType . '; q=' .
+            $DKIMquery . '; l=' .
+            $DKIMlen . '; s=' .
             $this->DKIM_selector .
             ";\r\n" .
-            "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n" .
+            "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
             "\th=From:To:Subject;\r\n" .
-            "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n" .
+            "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
             "\tz=$from\r\n" .
             "\t|$to\r\n" .
             "\t|$subject;\r\n" .
@@ -3229,6 +3324,56 @@ class PHPMailer
     }
 
     /**
+     * Allows for public read access to 'to' property.
+     * @access public
+     * @return array
+     */
+    public function getToAddresses()
+    {
+        return $this->to;
+    }
+
+    /**
+     * Allows for public read access to 'cc' property.
+     * @access public
+     * @return array
+     */
+    public function getCcAddresses()
+    {
+        return $this->cc;
+    }
+
+    /**
+     * Allows for public read access to 'bcc' property.
+     * @access public
+     * @return array
+     */
+    public function getBccAddresses()
+    {
+        return $this->bcc;
+    }
+
+    /**
+     * Allows for public read access to 'ReplyTo' property.
+     * @access public
+     * @return array
+     */
+    public function getReplyToAddresses()
+    {
+        return $this->ReplyTo;
+    }
+
+    /**
+     * Allows for public read access to 'all_recipients' property.
+     * @access public
+     * @return array
+     */
+    public function getAllRecipientAddresses()
+    {
+        return $this->all_recipients;
+    }
+
+    /**
      * Perform a callback.
      * @param bool $isSent
      * @param string $to
diff --git a/src/wp-includes/class-pop3.php b/src/wp-includes/class-pop3.php
index d0455d7..71dffac 100644
--- a/src/wp-includes/class-pop3.php
+++ b/src/wp-includes/class-pop3.php
@@ -1,652 +1,417 @@
 <?php
 /**
- * mail_fetch/setup.php
- *
- * Copyright (c) 1999-2011 CDI (cdi@thewebmasters.net) All Rights Reserved
- * Modified by Philippe Mingo 2001-2009 mingo@rotedic.com
- * An RFC 1939 compliant wrapper class for the POP3 protocol.
- *
- * Licensed under the GNU GPL. For full terms see the file COPYING.
- *
- * POP3 class
- *
- * @copyright 1999-2011 The SquirrelMail Project Team
- * @license http://opensource.org/licenses/gpl-license.php GNU Public License
- * @package plugins
- * @subpackage mail_fetch
+ * PHPMailer POP-Before-SMTP Authentication Class.
+ * PHP Version 5
+ * @package PHPMailer
+ * @link https://github.com/PHPMailer/PHPMailer/
+ * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
+ * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
+ * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
+ * @author Brent R. Matzelle (original founder)
+ * @copyright 2012 - 2014 Marcus Bointon
+ * @copyright 2010 - 2012 Jim Jagielski
+ * @copyright 2004 - 2009 Andy Prevost
+ * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
+ * @note This program is distributed in the hope that it will be useful - WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.
  */
 
-class POP3 {
-    var $ERROR      = '';       //  Error string.
-
-    var $TIMEOUT    = 60;       //  Default timeout before giving up on a
-                                //  network operation.
-
-    var $COUNT      = -1;       //  Mailbox msg count
-
-    var $BUFFER     = 512;      //  Socket buffer for socket fgets() calls.
-                                //  Per RFC 1939 the returned line a POP3
-                                //  server can send is 512 bytes.
-
-    var $FP         = '';       //  The connection to the server's
-                                //  file descriptor
-
-    var $MAILSERVER = '';       // Set this to hard code the server name
-
-    var $DEBUG      = FALSE;    // set to true to echo pop3
-                                // commands and responses to error_log
-                                // this WILL log passwords!
-
-    var $BANNER     = '';       //  Holds the banner returned by the
-                                //  pop server - used for apop()
-
-    var $ALLOWAPOP  = FALSE;    //  Allow or disallow apop()
-                                //  This must be set to true
-                                //  manually
-
-    function POP3 ( $server = '', $timeout = '' ) {
-        settype($this->BUFFER,"integer");
-        if( !empty($server) ) {
-            // Do not allow programs to alter MAILSERVER
-            // if it is already specified. They can get around
-            // this if they -really- want to, so don't count on it.
-            if(empty($this->MAILSERVER))
-                $this->MAILSERVER = $server;
-        }
-        if(!empty($timeout)) {
-            settype($timeout,"integer");
-            $this->TIMEOUT = $timeout;
-            if (!ini_get('safe_mode'))
-                set_time_limit($timeout);
-        }
-        return true;
+/**
+ * PHPMailer POP-Before-SMTP Authentication Class.
+ * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication.
+ * Does not support APOP.
+ * @package PHPMailer
+ * @author Richard Davey (original author) <rich@corephp.co.uk>
+ * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
+ * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
+ * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
+ */
+class POP3
+{
+    /**
+     * The POP3 PHPMailer Version number.
+     * @type string
+     * @access public
+     */
+    public $Version = '5.2.8';
+
+    /**
+     * Default POP3 port number.
+     * @type int
+     * @access public
+     */
+    public $POP3_PORT = 110;
+
+    /**
+     * Default timeout in seconds.
+     * @type int
+     * @access public
+     */
+    public $POP3_TIMEOUT = 30;
+
+    /**
+     * POP3 Carriage Return + Line Feed.
+     * @type string
+     * @access public
+     * @deprecated Use the constant instead
+     */
+    public $CRLF = "\r\n";
+
+    /**
+     * Debug display level.
+     * Options: 0 = no, 1+ = yes
+     * @type int
+     * @access public
+     */
+    public $do_debug = 0;
+
+    /**
+     * POP3 mail server hostname.
+     * @type string
+     * @access public
+     */
+    public $host;
+
+    /**
+     * POP3 port number.
+     * @type int
+     * @access public
+     */
+    public $port;
+
+    /**
+     * POP3 Timeout Value in seconds.
+     * @type int
+     * @access public
+     */
+    public $tval;
+
+    /**
+     * POP3 username
+     * @type string
+     * @access public
+     */
+    public $username;
+
+    /**
+     * POP3 password.
+     * @type string
+     * @access public
+     */
+    public $password;
+
+    /**
+     * Resource handle for the POP3 connection socket.
+     * @type resource
+     * @access private
+     */
+    private $pop_conn;
+
+    /**
+     * Are we connected?
+     * @type bool
+     * @access private
+     */
+    private $connected;
+
+    /**
+     * Error container.
+     * @type array
+     * @access private
+     */
+    private $error;
+
+    /**
+     * Line break constant
+     */
+    const CRLF = "\r\n";
+
+    /**
+     * Constructor.
+     * @access public
+     */
+    public function __construct()
+    {
+        $this->pop_conn = 0;
+        $this->connected = false;
+        $this->error = null;
     }
 
-    function update_timer () {
-        if (!ini_get('safe_mode'))
-            set_time_limit($this->TIMEOUT);
-        return true;
+    /**
+     * Simple static wrapper for all-in-one POP before SMTP
+     * @param $host
+     * @param bool $port
+     * @param bool $tval
+     * @param string $username
+     * @param string $password
+     * @param int $debug_level
+     * @return bool
+     */
+    public static function popBeforeSmtp(
+        $host,
+        $port = false,
+        $tval = false,
+        $username = '',
+        $password = '',
+        $debug_level = 0
+    ) {
+        $pop = new POP3;
+        return $pop->authorise($host, $port, $tval, $username, $password, $debug_level);
     }
 
-    function connect ($server, $port = 110)  {
-        //  Opens a socket to the specified server. Unless overridden,
-        //  port defaults to 110. Returns true on success, false on fail
-
-        // If MAILSERVER is set, override $server with it's value
-
-    if (!isset($port) || !$port) {$port = 110;}
-        if(!empty($this->MAILSERVER))
-            $server = $this->MAILSERVER;
-
-        if(empty($server)){
-            $this->ERROR = "POP3 connect: " . _("No server specified");
-            unset($this->FP);
-            return false;
-        }
-
-        $fp = @fsockopen("$server", $port, $errno, $errstr);
-
-        if(!$fp) {
-            $this->ERROR = "POP3 connect: " . _("Error ") . "[$errno] [$errstr]";
-            unset($this->FP);
-            return false;
-        }
-
-        socket_set_blocking($fp,-1);
-        $this->update_timer();
-        $reply = fgets($fp,$this->BUFFER);
-        $reply = $this->strip_clf($reply);
-        if($this->DEBUG)
-            error_log("POP3 SEND [connect: $server] GOT [$reply]",0);
-        if(!$this->is_ok($reply)) {
-            $this->ERROR = "POP3 connect: " . _("Error ") . "[$reply]";
-            unset($this->FP);
-            return false;
-        }
-        $this->FP = $fp;
-        $this->BANNER = $this->parse_banner($reply);
-        return true;
-    }
-
-    function user ($user = "") {
-        // Sends the USER command, returns true or false
-
-        if( empty($user) ) {
-            $this->ERROR = "POP3 user: " . _("no login ID submitted");
-            return false;
-        } elseif(!isset($this->FP)) {
-            $this->ERROR = "POP3 user: " . _("connection not established");
-            return false;
+    /**
+     * Authenticate with a POP3 server.
+     * A connect, login, disconnect sequence
+     * appropriate for POP-before SMTP authorisation.
+     * @access public
+     * @param string $host
+     * @param bool|int $port
+     * @param bool|int $tval
+     * @param string $username
+     * @param string $password
+     * @param int $debug_level
+     * @return bool
+     */
+    public function authorise($host, $port = false, $tval = false, $username = '', $password = '', $debug_level = 0)
+    {
+        $this->host = $host;
+        // If no port value provided, use default
+        if ($port === false) {
+            $this->port = $this->POP3_PORT;
         } else {
-            $reply = $this->send_cmd("USER $user");
-            if(!$this->is_ok($reply)) {
-                $this->ERROR = "POP3 user: " . _("Error ") . "[$reply]";
-                return false;
-            } else
-                return true;
+            $this->port = $port;
         }
-    }
-
-    function pass ($pass = "")     {
-        // Sends the PASS command, returns # of msgs in mailbox,
-        // returns false (undef) on Auth failure
-
-        if(empty($pass)) {
-            $this->ERROR = "POP3 pass: " . _("No password submitted");
-            return false;
-        } elseif(!isset($this->FP)) {
-            $this->ERROR = "POP3 pass: " . _("connection not established");
-            return false;
+        // If no timeout value provided, use default
+        if ($tval === false) {
+            $this->tval = $this->POP3_TIMEOUT;
         } else {
-            $reply = $this->send_cmd("PASS $pass");
-            if(!$this->is_ok($reply)) {
-                $this->ERROR = "POP3 pass: " . _("Authentication failed") . " [$reply]";
-                $this->quit();
-                return false;
-            } else {
-                //  Auth successful.
-                $count = $this->last("count");
-                $this->COUNT = $count;
-                return $count;
+            $this->tval = $tval;
+        }
+        $this->do_debug = $debug_level;
+        $this->username = $username;
+        $this->password = $password;
+        //  Refresh the error log
+        $this->error = null;
+        //  connect
+        $result = $this->connect($this->host, $this->port, $this->tval);
+        if ($result) {
+            $login_result = $this->login($this->username, $this->password);
+            if ($login_result) {
+                $this->disconnect();
+                return true;
             }
         }
+        // We need to disconnect regardless of whether the login succeeded
+        $this->disconnect();
+        return false;
     }
 
-    function apop ($login,$pass) {
-        //  Attempts an APOP login. If this fails, it'll
-        //  try a standard login. YOUR SERVER MUST SUPPORT
-        //  THE USE OF THE APOP COMMAND!
-        //  (apop is optional per rfc1939)
-
-        if(!isset($this->FP)) {
-            $this->ERROR = "POP3 apop: " . _("No connection to server");
-            return false;
-        } elseif(!$this->ALLOWAPOP) {
-            $retVal = $this->login($login,$pass);
-            return $retVal;
-        } elseif(empty($login)) {
-            $this->ERROR = "POP3 apop: " . _("No login ID submitted");
-            return false;
-        } elseif(empty($pass)) {
-            $this->ERROR = "POP3 apop: " . _("No password submitted");
-            return false;
-        } else {
-            $banner = $this->BANNER;
-            if( (!$banner) or (empty($banner)) ) {
-                $this->ERROR = "POP3 apop: " . _("No server banner") . ' - ' . _("abort");
-                $retVal = $this->login($login,$pass);
-                return $retVal;
-            } else {
-                $AuthString = $banner;
-                $AuthString .= $pass;
-                $APOPString = md5($AuthString);
-                $cmd = "APOP $login $APOPString";
-                $reply = $this->send_cmd($cmd);
-                if(!$this->is_ok($reply)) {
-                    $this->ERROR = "POP3 apop: " . _("apop authentication failed") . ' - ' . _("abort");
-                    $retVal = $this->login($login,$pass);
-                    return $retVal;
-                } else {
-                    //  Auth successful.
-                    $count = $this->last("count");
-                    $this->COUNT = $count;
-                    return $count;
-                }
+    /**
+     * Connect to a POP3 server.
+     * @access public
+     * @param string $host
+     * @param bool|int $port
+     * @param integer $tval
+     * @return boolean
+     */
+    public function connect($host, $port = false, $tval = 30)
+    {
+        //  Are we already connected?
+        if ($this->connected) {
+            return true;
+        }
+
+        //On Windows this will raise a PHP Warning error if the hostname doesn't exist.
+        //Rather than suppress it with @fsockopen, capture it cleanly instead
+        set_error_handler(array($this, 'catchWarning'));
+
+        //  connect to the POP3 server
+        $this->pop_conn = fsockopen(
+            $host, //  POP3 Host
+            $port, //  Port #
+            $errno, //  Error Number
+            $errstr, //  Error Message
+            $tval
+        ); //  Timeout (seconds)
+        //  Restore the error handler
+        restore_error_handler();
+        //  Does the Error Log now contain anything?
+        if ($this->error && $this->do_debug >= 1) {
+            $this->displayErrors();
+        }
+        //  Did we connect?
+        if ($this->pop_conn == false) {
+            //  It would appear not...
+            $this->error = array(
+                'error' => "Failed to connect to server $host on port $port",
+                'errno' => $errno,
+                'errstr' => $errstr
+            );
+            if ($this->do_debug >= 1) {
+                $this->displayErrors();
             }
+            return false;
         }
-    }
 
-    function login ($login = "", $pass = "") {
-        // Sends both user and pass. Returns # of msgs in mailbox or
-        // false on failure (or -1, if the error occurs while getting
-        // the number of messages.)
-
-        if( !isset($this->FP) ) {
-            $this->ERROR = "POP3 login: " . _("No connection to server");
-            return false;
+        //  Increase the stream time-out
+        //  Check for PHP 4.3.0 or later
+        if (version_compare(phpversion(), '5.0.0', 'ge')) {
+            stream_set_timeout($this->pop_conn, $tval, 0);
         } else {
-            $fp = $this->FP;
-            if( !$this->user( $login ) ) {
-                //  Preserve the error generated by user()
-                return false;
-            } else {
-                $count = $this->pass($pass);
-                if( (!$count) || ($count == -1) ) {
-                    //  Preserve the error generated by last() and pass()
-                    return false;
-                } else
-                    return $count;
+            //  Does not work on Windows
+            if (substr(PHP_OS, 0, 3) !== 'WIN') {
+                socket_set_timeout($this->pop_conn, $tval, 0);
             }
         }
-    }
-
-    function top ($msgNum, $numLines = "0") {
-        //  Gets the header and first $numLines of the msg body
-        //  returns data in an array with each returned line being
-        //  an array element. If $numLines is empty, returns
-        //  only the header information, and none of the body.
-
-        if(!isset($this->FP)) {
-            $this->ERROR = "POP3 top: " . _("No connection to server");
-            return false;
-        }
-        $this->update_timer();
-
-        $fp = $this->FP;
-        $buffer = $this->BUFFER;
-        $cmd = "TOP $msgNum $numLines";
-        fwrite($fp, "TOP $msgNum $numLines\r\n");
-        $reply = fgets($fp, $buffer);
-        $reply = $this->strip_clf($reply);
-        if($this->DEBUG) {
-            @error_log("POP3 SEND [$cmd] GOT [$reply]",0);
-        }
-        if(!$this->is_ok($reply))
-        {
-            $this->ERROR = "POP3 top: " . _("Error ") . "[$reply]";
-            return false;
-        }
 
-        $count = 0;
-        $MsgArray = array();
-
-        $line = fgets($fp,$buffer);
-        while ( !preg_match('/^\.\r\n/',$line))
-        {
-            $MsgArray[$count] = $line;
-            $count++;
-            $line = fgets($fp,$buffer);
-            if(empty($line))    { break; }
+        //  Get the POP3 server response
+        $pop3_response = $this->getResponse();
+        //  Check for the +OK
+        if ($this->checkResponse($pop3_response)) {
+            //  The connection is established and the POP3 server is talking
+            $this->connected = true;
+            return true;
         }
-
-        return $MsgArray;
+        return false;
     }
 
-    function pop_list ($msgNum = "") {
-        //  If called with an argument, returns that msgs' size in octets
-        //  No argument returns an associative array of undeleted
-        //  msg numbers and their sizes in octets
-
-        if(!isset($this->FP))
-        {
-            $this->ERROR = "POP3 pop_list: " . _("No connection to server");
-            return false;
-        }
-        $fp = $this->FP;
-        $Total = $this->COUNT;
-        if( (!$Total) or ($Total == -1) )
-        {
-            return false;
-        }
-        if($Total == 0)
-        {
-            return array("0","0");
-            // return -1;   // mailbox empty
-        }
-
-        $this->update_timer();
+    /**
+     * Log in to the POP3 server.
+     * Does not support APOP (RFC 2828, 4949).
+     * @access public
+     * @param string $username
+     * @param string $password
+     * @return boolean
+     */
+    public function login($username = '', $password = '')
+    {
+        if ($this->connected == false) {
+            $this->error = 'Not connected to POP3 server';
 
-        if(!empty($msgNum))
-        {
-            $cmd = "LIST $msgNum";
-            fwrite($fp,"$cmd\r\n");
-            $reply = fgets($fp,$this->BUFFER);
-            $reply = $this->strip_clf($reply);
-            if($this->DEBUG) {
-                @error_log("POP3 SEND [$cmd] GOT [$reply]",0);
+            if ($this->do_debug >= 1) {
+                $this->displayErrors();
             }
-            if(!$this->is_ok($reply))
-            {
-                $this->ERROR = "POP3 pop_list: " . _("Error ") . "[$reply]";
-                return false;
-            }
-            list($junk,$num,$size) = preg_split('/\s+/',$reply);
-            return $size;
         }
-        $cmd = "LIST";
-        $reply = $this->send_cmd($cmd);
-        if(!$this->is_ok($reply))
-        {
-            $reply = $this->strip_clf($reply);
-            $this->ERROR = "POP3 pop_list: " . _("Error ") .  "[$reply]";
-            return false;
+        if (empty($username)) {
+            $username = $this->username;
         }
-        $MsgArray = array();
-        $MsgArray[0] = $Total;
-        for($msgC=1;$msgC <= $Total; $msgC++)
-        {
-            if($msgC > $Total) { break; }
-            $line = fgets($fp,$this->BUFFER);
-            $line = $this->strip_clf($line);
-            if(strpos($line, '.') === 0)
-            {
-                $this->ERROR = "POP3 pop_list: " . _("Premature end of list");
-                return false;
-            }
-            list($thisMsg,$msgSize) = preg_split('/\s+/',$line);
-            settype($thisMsg,"integer");
-            if($thisMsg != $msgC)
-            {
-                $MsgArray[$msgC] = "deleted";
-            }
-            else
-            {
-                $MsgArray[$msgC] = $msgSize;
-            }
+        if (empty($password)) {
+            $password = $this->password;
         }
-        return $MsgArray;
-    }
-
-    function get ($msgNum) {
-        //  Retrieve the specified msg number. Returns an array
-        //  where each line of the msg is an array element.
 
-        if(!isset($this->FP))
-        {
-            $this->ERROR = "POP3 get: " . _("No connection to server");
-            return false;
-        }
-
-        $this->update_timer();
-
-        $fp = $this->FP;
-        $buffer = $this->BUFFER;
-        $cmd = "RETR $msgNum";
-        $reply = $this->send_cmd($cmd);
-
-        if(!$this->is_ok($reply))
-        {
-            $this->ERROR = "POP3 get: " . _("Error ") . "[$reply]";
-            return false;
-        }
-
-        $count = 0;
-        $MsgArray = array();
-
-        $line = fgets($fp,$buffer);
-        while ( !preg_match('/^\.\r\n/',$line))
-        {
-            if ( $line{0} == '.' ) { $line = substr($line,1); }
-            $MsgArray[$count] = $line;
-            $count++;
-            $line = fgets($fp,$buffer);
-            if(empty($line))    { break; }
-        }
-        return $MsgArray;
-    }
-
-    function last ( $type = "count" ) {
-        //  Returns the highest msg number in the mailbox.
-        //  returns -1 on error, 0+ on success, if type != count
-        //  results in a popstat() call (2 element array returned)
-
-        $last = -1;
-        if(!isset($this->FP))
-        {
-            $this->ERROR = "POP3 last: " . _("No connection to server");
-            return $last;
-        }
-
-        $reply = $this->send_cmd("STAT");
-        if(!$this->is_ok($reply))
-        {
-            $this->ERROR = "POP3 last: " . _("Error ") . "[$reply]";
-            return $last;
-        }
-
-        $Vars = preg_split('/\s+/',$reply);
-        $count = $Vars[1];
-        $size = $Vars[2];
-        settype($count,"integer");
-        settype($size,"integer");
-        if($type != "count")
-        {
-            return array($count,$size);
-        }
-        return $count;
-    }
-
-    function reset () {
-        //  Resets the status of the remote server. This includes
-        //  resetting the status of ALL msgs to not be deleted.
-        //  This method automatically closes the connection to the server.
-
-        if(!isset($this->FP))
-        {
-            $this->ERROR = "POP3 reset: " . _("No connection to server");
-            return false;
-        }
-        $reply = $this->send_cmd("RSET");
-        if(!$this->is_ok($reply))
-        {
-            //  The POP3 RSET command -never- gives a -ERR
-            //  response - if it ever does, something truely
-            //  wild is going on.
-
-            $this->ERROR = "POP3 reset: " . _("Error ") . "[$reply]";
-            @error_log("POP3 reset: ERROR [$reply]",0);
+        // Send the Username
+        $this->sendString("USER $username" . self::CRLF);
+        $pop3_response = $this->getResponse();
+        if ($this->checkResponse($pop3_response)) {
+            // Send the Password
+            $this->sendString("PASS $password" . self::CRLF);
+            $pop3_response = $this->getResponse();
+            if ($this->checkResponse($pop3_response)) {
+                return true;
+            }
         }
-        $this->quit();
-        return true;
+        return false;
     }
 
-    function send_cmd ( $cmd = "" )
+    /**
+     * Disconnect from the POP3 server.
+     * @access public
+     */
+    public function disconnect()
     {
-        //  Sends a user defined command string to the
-        //  POP server and returns the results. Useful for
-        //  non-compliant or custom POP servers.
-        //  Do NOT includ the \r\n as part of your command
-        //  string - it will be appended automatically.
-
-        //  The return value is a standard fgets() call, which
-        //  will read up to $this->BUFFER bytes of data, until it
-        //  encounters a new line, or EOF, whichever happens first.
-
-        //  This method works best if $cmd responds with only
-        //  one line of data.
-
-        if(!isset($this->FP))
-        {
-            $this->ERROR = "POP3 send_cmd: " . _("No connection to server");
-            return false;
-        }
-
-        if(empty($cmd))
-        {
-            $this->ERROR = "POP3 send_cmd: " . _("Empty command string");
-            return "";
-        }
-
-        $fp = $this->FP;
-        $buffer = $this->BUFFER;
-        $this->update_timer();
-        fwrite($fp,"$cmd\r\n");
-        $reply = fgets($fp,$buffer);
-        $reply = $this->strip_clf($reply);
-        if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); }
-        return $reply;
+        $this->sendString('QUIT');
+        //The QUIT command may cause the daemon to exit, which will kill our connection
+        //So ignore errors here
+        @fclose($this->pop_conn);
     }
 
-    function quit() {
-        //  Closes the connection to the POP3 server, deleting
-        //  any msgs marked as deleted.
-
-        if(!isset($this->FP))
-        {
-            $this->ERROR = "POP3 quit: " . _("connection does not exist");
-            return false;
-        }
-        $fp = $this->FP;
-        $cmd = "QUIT";
-        fwrite($fp,"$cmd\r\n");
-        $reply = fgets($fp,$this->BUFFER);
-        $reply = $this->strip_clf($reply);
-        if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); }
-        fclose($fp);
-        unset($this->FP);
-        return true;
-    }
-
-    function popstat () {
-        //  Returns an array of 2 elements. The number of undeleted
-        //  msgs in the mailbox, and the size of the mbox in octets.
-
-        $PopArray = $this->last("array");
-
-        if($PopArray == -1) { return false; }
-
-        if( (!$PopArray) or (empty($PopArray)) )
-        {
-            return false;
+    /**
+     * Get a response from the POP3 server.
+     * $size is the maximum number of bytes to retrieve
+     * @param integer $size
+     * @return string
+     * @access private
+     */
+    private function getResponse($size = 128)
+    {
+        $response = fgets($this->pop_conn, $size);
+        if ($this->do_debug >= 1) {
+            echo "Server -> Client: $response";
         }
-        return $PopArray;
+        return $response;
     }
 
-    function uidl ($msgNum = "")
+    /**
+     * Send raw data to the POP3 server.
+     * @param string $string
+     * @return integer
+     * @access private
+     */
+    private function sendString($string)
     {
-        //  Returns the UIDL of the msg specified. If called with
-        //  no arguments, returns an associative array where each
-        //  undeleted msg num is a key, and the msg's uidl is the element
-        //  Array element 0 will contain the total number of msgs
-
-        if(!isset($this->FP)) {
-            $this->ERROR = "POP3 uidl: " . _("No connection to server");
-            return false;
-        }
-
-        $fp = $this->FP;
-        $buffer = $this->BUFFER;
-
-        if(!empty($msgNum)) {
-            $cmd = "UIDL $msgNum";
-            $reply = $this->send_cmd($cmd);
-            if(!$this->is_ok($reply))
-            {
-                $this->ERROR = "POP3 uidl: " . _("Error ") . "[$reply]";
-                return false;
+        if ($this->pop_conn) {
+            if ($this->do_debug >= 2) { //Show client messages when debug >= 2
+                echo "Client -> Server: $string";
             }
-            list ($ok,$num,$myUidl) = preg_split('/\s+/',$reply);
-            return $myUidl;
-        } else {
-            $this->update_timer();
-
-            $UIDLArray = array();
-            $Total = $this->COUNT;
-            $UIDLArray[0] = $Total;
-
-            if ($Total < 1)
-            {
-                return $UIDLArray;
-            }
-            $cmd = "UIDL";
-            fwrite($fp, "UIDL\r\n");
-            $reply = fgets($fp, $buffer);
-            $reply = $this->strip_clf($reply);
-            if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); }
-            if(!$this->is_ok($reply))
-            {
-                $this->ERROR = "POP3 uidl: " . _("Error ") . "[$reply]";
-                return false;
-            }
-
-            $line = "";
-            $count = 1;
-            $line = fgets($fp,$buffer);
-            while ( !preg_match('/^\.\r\n/',$line)) {
-                list ($msg,$msgUidl) = preg_split('/\s+/',$line);
-                $msgUidl = $this->strip_clf($msgUidl);
-                if($count == $msg) {
-                    $UIDLArray[$msg] = $msgUidl;
-                }
-                else
-                {
-                    $UIDLArray[$count] = 'deleted';
-                }
-                $count++;
-                $line = fgets($fp,$buffer);
-            }
-        }
-        return $UIDLArray;
-    }
-
-    function delete ($msgNum = "") {
-        //  Flags a specified msg as deleted. The msg will not
-        //  be deleted until a quit() method is called.
-
-        if(!isset($this->FP))
-        {
-            $this->ERROR = "POP3 delete: " . _("No connection to server");
-            return false;
-        }
-        if(empty($msgNum))
-        {
-            $this->ERROR = "POP3 delete: " . _("No msg number submitted");
-            return false;
-        }
-        $reply = $this->send_cmd("DELE $msgNum");
-        if(!$this->is_ok($reply))
-        {
-            $this->ERROR = "POP3 delete: " . _("Command failed ") . "[$reply]";
-            return false;
+            return fwrite($this->pop_conn, $string, strlen($string));
         }
-        return true;
+        return 0;
     }
 
-    //  *********************************************************
-
-    //  The following methods are internal to the class.
-
-    function is_ok ($cmd = "") {
-        //  Return true or false on +OK or -ERR
-
-        if( empty($cmd) )
+    /**
+     * Checks the POP3 server response.
+     * Looks for for +OK or -ERR.
+     * @param string $string
+     * @return boolean
+     * @access private
+     */
+    private function checkResponse($string)
+    {
+        if (substr($string, 0, 3) !== '+OK') {
+            $this->error = array(
+                'error' => "Server reported an error: $string",
+                'errno' => 0,
+                'errstr' => ''
+            );
+            if ($this->do_debug >= 1) {
+                $this->displayErrors();
+            }
             return false;
-        else
-            return( stripos($cmd, '+OK') !== false );
-    }
-
-    function strip_clf ($text = "") {
-        // Strips \r\n from server responses
-
-        if(empty($text))
-            return $text;
-        else {
-            $stripped = str_replace(array("\r","\n"),'',$text);
-            return $stripped;
+        } else {
+            return true;
         }
     }
 
-    function parse_banner ( $server_text ) {
-        $outside = true;
-        $banner = "";
-        $length = strlen($server_text);
-        for($count =0; $count < $length; $count++)
-        {
-            $digit = substr($server_text,$count,1);
-            if(!empty($digit))             {
-                if( (!$outside) && ($digit != '<') && ($digit != '>') )
-                {
-                    $banner .= $digit;
-                }
-                if ($digit == '<')
-                {
-                    $outside = false;
-                }
-                if($digit == '>')
-                {
-                    $outside = true;
-                }
-            }
+    /**
+     * Display errors if debug is enabled.
+     * @access private
+     */
+    private function displayErrors()
+    {
+        echo '<pre>';
+        foreach ($this->error as $single_error) {
+            print_r($single_error);
         }
-        $banner = $this->strip_clf($banner);    // Just in case
-        return "<$banner>";
+        echo '</pre>';
     }
 
-}   // End class
-
-// For php4 compatibility
-if (!function_exists("stripos")) {
-    function stripos($haystack, $needle){
-        return strpos($haystack, stristr( $haystack, $needle ));
+    /**
+     * POP3 connection error handler.
+     * @param integer $errno
+     * @param string $errstr
+     * @param string $errfile
+     * @param integer $errline
+     * @access private
+     */
+    private function catchWarning($errno, $errstr, $errfile, $errline)
+    {
+        $this->error[] = array(
+            'error' => "Connecting to the POP3 server raised a PHP warning: ",
+            'errno' => $errno,
+            'errstr' => $errstr,
+            'errfile' => $errfile,
+            'errline' => $errline
+        );
     }
 }
diff --git a/src/wp-includes/class-smtp.php b/src/wp-includes/class-smtp.php
index e6b4522..ec75ca5 100644
--- a/src/wp-includes/class-smtp.php
+++ b/src/wp-includes/class-smtp.php
@@ -1,102 +1,117 @@
 <?php
 /**
  * PHPMailer RFC821 SMTP email transport class.
- * Version 5.2.7
- * PHP version 5.0.0
- * @category  PHP
- * @package   PHPMailer
- * @link      https://github.com/PHPMailer/PHPMailer/
- * @author Marcus Bointon (coolbru) <phpmailer@synchromedia.co.uk>
+ * PHP Version 5
+ * @package PHPMailer
+ * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
+ * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
- * @copyright 2013 Marcus Bointon
- * @copyright 2004 - 2008 Andy Prevost
+ * @author Brent R. Matzelle (original founder)
+ * @copyright 2014 Marcus Bointon
  * @copyright 2010 - 2012 Jim Jagielski
- * @license   http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
+ * @copyright 2004 - 2009 Andy Prevost
+ * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
+ * @note This program is distributed in the hope that it will be useful - WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.
  */
 
 /**
  * PHPMailer RFC821 SMTP email transport class.
- *
- * Implements RFC 821 SMTP commands
- * and provides some utility methods for sending mail to an SMTP server.
- *
- * PHP Version 5.0.0
- *
- * @category PHP
- * @package  PHPMailer
- * @link     https://github.com/PHPMailer/PHPMailer/blob/master/class.smtp.php
- * @author   Chris Ryan <unknown@example.com>
- * @author   Marcus Bointon <phpmailer@synchromedia.co.uk>
- * @license  http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
+ * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
+ * @package PHPMailer
+ * @author Chris Ryan <unknown@example.com>
+ * @author Marcus Bointon <phpmailer@synchromedia.co.uk>
  */
-
 class SMTP
 {
     /**
-     * The PHPMailer SMTP Version number.
+     * The PHPMailer SMTP version number.
+     * @type string
      */
-    const VERSION = '5.2.7';
+    const VERSION = '5.2.8';
 
     /**
      * SMTP line break constant.
+     * @type string
      */
     const CRLF = "\r\n";
 
     /**
      * The SMTP port to use if one is not specified.
+     * @type int
      */
     const DEFAULT_SMTP_PORT = 25;
 
     /**
+     * The maximum line length allowed by RFC 2822 section 2.1.1
+     * @type int
+     */
+    const MAX_LINE_LENGTH = 998;
+
+    /**
      * The PHPMailer SMTP Version number.
      * @type string
-     * @deprecated This should be a constant
+     * @deprecated Use the constant instead
      * @see SMTP::VERSION
      */
-    public $Version = '5.2.7';
+    public $Version = '5.2.8';
 
     /**
      * SMTP server port number.
      * @type int
-     * @deprecated This is only ever ued as default value, so should be a constant
+     * @deprecated This is only ever used as a default value, so use the constant instead
      * @see SMTP::DEFAULT_SMTP_PORT
      */
     public $SMTP_PORT = 25;
 
     /**
-     * SMTP reply line ending
+     * SMTP reply line ending.
      * @type string
-     * @deprecated Use the class constant instead
+     * @deprecated Use the constant instead
      * @see SMTP::CRLF
      */
     public $CRLF = "\r\n";
 
     /**
      * Debug output level.
-     * Options: 0 for no output, 1 for commands, 2 for data and commands
+     * Options:
+     * * `0` No output
+     * * `1` Commands
+     * * `2` Data and commands
+     * * `3` As 2 plus connection status
+     * * `4` Low-level data output
      * @type int
      */
     public $do_debug = 0;
 
     /**
-     * The function/method to use for debugging output.
-     * Options: 'echo', 'html' or 'error_log'
+     * How to handle debug output.
+     * Options:
+     * * `echo` Output plain-text as-is, appropriate for CLI
+     * * `html` Output escaped, line breaks converted to <br>, appropriate for browser output
+     * * `error_log` Output to error log as configured in php.ini
      * @type string
      */
     public $Debugoutput = 'echo';
 
     /**
      * Whether to use VERP.
+     * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
+     * @link http://www.postfix.org/VERP_README.html Info on VERP
      * @type bool
      */
     public $do_verp = false;
 
     /**
-     * The SMTP timeout value for reads, in seconds.
+     * The timeout value for connection, in seconds.
+     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
+     * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
+     * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2
      * @type int
      */
-    public $Timeout = 15;
+    public $Timeout = 300;
 
     /**
      * The SMTP timelimit value for reads, in seconds.
@@ -137,7 +152,6 @@ class SMTP
         $this->smtp_conn = 0;
         $this->error = null;
         $this->helo_rply = null;
-
         $this->do_debug = 0;
     }
 
@@ -164,15 +178,14 @@ class SMTP
                 break;
             case 'echo':
             default:
-                //Just echoes whatever was received
-                echo $str;
+                echo gmdate('Y-m-d H:i:s')."\t".trim($str)."\n";
         }
     }
 
     /**
      * Connect to an SMTP server.
-     * @param string $host    SMTP server IP or host name
-     * @param int $port    The port number to connect to
+     * @param string $host SMTP server IP or host name
+     * @param int $port The port number to connect to
      * @param int $timeout How long to wait for the connection to open
      * @param array $options An array of options for stream_context_create()
      * @access public
@@ -182,19 +195,19 @@ class SMTP
     {
         // Clear errors to avoid confusion
         $this->error = null;
-
         // Make sure we are __not__ connected
         if ($this->connected()) {
             // Already connected, generate error
             $this->error = array('error' => 'Already connected to a server');
             return false;
         }
-
         if (empty($port)) {
             $port = self::DEFAULT_SMTP_PORT;
         }
-
         // Connect to the SMTP server
+        if ($this->do_debug >= 3) {
+            $this->edebug('Connection: opening');
+        }
         $errno = 0;
         $errstr = '';
         $socket_context = stream_context_create($options);
@@ -207,7 +220,6 @@ class SMTP
             STREAM_CLIENT_CONNECT,
             $socket_context
         );
-
         // Verify we connected properly
         if (empty($this->smtp_conn)) {
             $this->error = array(
@@ -217,13 +229,15 @@ class SMTP
             );
             if ($this->do_debug >= 1) {
                 $this->edebug(
-                    'SMTP -> ERROR: ' . $this->error['error']
+                    'SMTP ERROR: ' . $this->error['error']
                     . ": $errstr ($errno)"
                 );
             }
             return false;
         }
-
+        if ($this->do_debug >= 3) {
+            $this->edebug('Connection: opened');
+        }
         // SMTP server can take longer to respond, give longer timeout for first read
         // Windows does not have support for this timeout function
         if (substr(PHP_OS, 0, 3) != 'WIN') {
@@ -233,14 +247,11 @@ class SMTP
             }
             stream_set_timeout($this->smtp_conn, $timeout, 0);
         }
-
         // Get any announcement
         $announce = $this->get_lines();
-
         if ($this->do_debug >= 2) {
-            $this->edebug('SMTP -> FROM SERVER:' . $announce);
+            $this->edebug('SERVER -> CLIENT: ' . $announce);
         }
-
         return true;
     }
 
@@ -251,7 +262,7 @@ class SMTP
      */
     public function startTLS()
     {
-        if (!$this->sendCommand("STARTTLS", "STARTTLS", 220)) {
+        if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
             return false;
         }
         // Begin encrypted connection
@@ -259,8 +270,7 @@ class SMTP
             $this->smtp_conn,
             true,
             STREAM_CRYPTO_METHOD_TLS_CLIENT
-        )
-        ) {
+        )) {
             return false;
         }
         return true;
@@ -288,7 +298,6 @@ class SMTP
         if (empty($authtype)) {
             $authtype = 'LOGIN';
         }
-
         switch ($authtype) {
             case 'PLAIN':
                 // Start authentication
@@ -351,7 +360,6 @@ class SMTP
                 ) {
                     return false;
                 }
-
                 //Though 0 based, there is a white space after the 3 digit number
                 //msg2
                 $challenge = substr($this->last_reply, 3);
@@ -411,13 +419,13 @@ class SMTP
         // Eliminates the need to install mhash to compute a HMAC
         // Hacked by Lance Rushing
 
-        $b = 64; // byte length for md5
-        if (strlen($key) > $b) {
+        $bytelen = 64; // byte length for md5
+        if (strlen($key) > $bytelen) {
             $key = pack('H*', md5($key));
         }
-        $key = str_pad($key, $b, chr(0x00));
-        $ipad = str_pad('', $b, chr(0x36));
-        $opad = str_pad('', $b, chr(0x5c));
+        $key = str_pad($key, $bytelen, chr(0x00));
+        $ipad = str_pad('', $bytelen, chr(0x36));
+        $opad = str_pad('', $bytelen, chr(0x5c));
         $k_ipad = $key ^ $ipad;
         $k_opad = $key ^ $opad;
 
@@ -437,7 +445,7 @@ class SMTP
                 // the socket is valid but we are not connected
                 if ($this->do_debug >= 1) {
                     $this->edebug(
-                        'SMTP -> NOTICE: EOF caught while checking if connected'
+                        'SMTP NOTICE: EOF caught while checking if connected'
                     );
                 }
                 $this->close();
@@ -462,6 +470,9 @@ class SMTP
         if (!empty($this->smtp_conn)) {
             // close the connection and cleanup
             fclose($this->smtp_conn);
+            if ($this->do_debug >= 3) {
+                $this->edebug('Connection: closed');
+            }
             $this->smtp_conn = 0;
         }
     }
@@ -483,62 +494,52 @@ class SMTP
         if (!$this->sendCommand('DATA', 'DATA', 354)) {
             return false;
         }
-
         /* The server is ready to accept data!
-         * according to rfc821 we should not send more than 1000
-         * including the CRLF
-         * characters on a single line so we will break the data up
-         * into lines by \r and/or \n then if needed we will break
-         * each of those into smaller lines to fit within the limit.
-         * in addition we will be looking for lines that start with
-         * a period '.' and append and additional period '.' to that
-         * line. NOTE: this does not count towards limit.
+         * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
+         * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
+         * smaller lines to fit within the limit.
+         * We will also look for lines that start with a '.' and prepend an additional '.'.
+         * NOTE: this does not count towards line-length limit.
          */
 
-        // Normalize the line breaks before exploding
-        $msg_data = str_replace("\r\n", "\n", $msg_data);
-        $msg_data = str_replace("\r", "\n", $msg_data);
-        $lines = explode("\n", $msg_data);
-
-        /* We need to find a good way to determine if headers are
-         * in the msg_data or if it is a straight msg body
-         * currently I am assuming rfc822 definitions of msg headers
-         * and if the first field of the first line (':' separated)
-         * does not contain a space then it _should_ be a header
-         * and we can process all lines before a blank "" line as
-         * headers.
+        // Normalize line breaks before exploding
+        $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
+
+        /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
+         * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
+         * process all lines before a blank line as headers.
          */
 
         $field = substr($lines[0], 0, strpos($lines[0], ':'));
         $in_headers = false;
-        if (!empty($field) && !strstr($field, ' ')) {
+        if (!empty($field) && strpos($field, ' ') === false) {
             $in_headers = true;
         }
 
-        //RFC 2822 section 2.1.1 limit
-        $max_line_length = 998;
-
         foreach ($lines as $line) {
-            $lines_out = null;
-            if ($line == '' && $in_headers) {
+            $lines_out = array();
+            if ($in_headers and $line == '') {
                 $in_headers = false;
             }
             // ok we need to break this line up into several smaller lines
-            while (strlen($line) > $max_line_length) {
-                $pos = strrpos(substr($line, 0, $max_line_length), ' ');
-
-                // Patch to fix DOS attack
-                if (!$pos) {
-                    $pos = $max_line_length - 1;
+            //This is a small micro-optimisation: isset($str[$len]) is equivalent to (strlen($str) > $len)
+            while (isset($line[self::MAX_LINE_LENGTH])) {
+                //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
+                //so as to avoid breaking in the middle of a word
+                $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
+                if (!$pos) { //Deliberately matches both false and 0
+                    //No nice break found, add a hard break
+                    $pos = self::MAX_LINE_LENGTH - 1;
                     $lines_out[] = substr($line, 0, $pos);
                     $line = substr($line, $pos);
                 } else {
+                    //Break at the found point
                     $lines_out[] = substr($line, 0, $pos);
+                    //Move along by the amount we dealt with
                     $line = substr($line, $pos + 1);
                 }
-
                 /* If processing headers add a LWSP-char to the front of new line
-                 * rfc822 on long msg headers
+                 * RFC822 section 3.1.1
                  */
                 if ($in_headers) {
                     $line = "\t" . $line;
@@ -546,12 +547,11 @@ class SMTP
             }
             $lines_out[] = $line;
 
-            // send the lines to the server
-            while (list(, $line_out) = @each($lines_out)) {
-                if (strlen($line_out) > 0) {
-                    if (substr($line_out, 0, 1) == '.') {
-                        $line_out = '.' . $line_out;
-                    }
+            // Send the lines to the server
+            foreach ($lines_out as $line_out) {
+                //RFC2821 section 4.5.2
+                if (!empty($line_out) and $line_out[0] == '.') {
+                    $line_out = '.' . $line_out;
                 }
                 $this->client_send($line_out . self::CRLF);
             }
@@ -565,7 +565,7 @@ class SMTP
      * Send an SMTP HELO or EHLO command.
      * Used to identify the sending server to the receiving server.
      * This makes sure that client and server are in a known state.
-     * Implements from RFC 821: HELO <SP> <domain> <CRLF>
+     * Implements RFC 821: HELO <SP> <domain> <CRLF>
      * and RFC 2821 EHLO.
      * @param string $host The host name or IP to connect to
      * @access public
@@ -574,13 +574,7 @@ class SMTP
     public function hello($host = '')
     {
         // Try extended hello first (RFC 2821)
-        if (!$this->sendHello('EHLO', $host)) {
-            if (!$this->sendHello('HELO', $host)) {
-                return false;
-            }
-        }
-
-        return true;
+        return (bool)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
     }
 
     /**
@@ -588,7 +582,7 @@ class SMTP
      * Low-level implementation used by hello()
      * @see hello()
      * @param string $hello The HELO string
-     * @param string $host  The hostname to say we are
+     * @param string $host The hostname to say we are
      * @access protected
      * @return bool
      */
@@ -631,28 +625,28 @@ class SMTP
     public function quit($close_on_error = true)
     {
         $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
-        $e = $this->error; //Save any error
+        $err = $this->error; //Save any error
         if ($noerror or $close_on_error) {
             $this->close();
-            $this->error = $e; //Restore any error from the quit command
+            $this->error = $err; //Restore any error from the quit command
         }
         return $noerror;
     }
 
     /**
      * Send an SMTP RCPT command.
-     * Sets the TO argument to $to.
+     * Sets the TO argument to $toaddr.
      * Returns true if the recipient was accepted false if it was rejected.
      * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
-     * @param string $to The address the message is being sent to
+     * @param string $toaddr The address the message is being sent to
      * @access public
      * @return bool
      */
-    public function recipient($to)
+    public function recipient($toaddr)
     {
         return $this->sendCommand(
-            'RCPT TO ',
-            'RCPT TO:<' . $to . '>',
+            'RCPT TO',
+            'RCPT TO:<' . $toaddr . '>',
             array(250, 251)
         );
     }
@@ -681,7 +675,7 @@ class SMTP
     {
         if (!$this->connected()) {
             $this->error = array(
-                "error" => "Called $command without being connected"
+                'error' => "Called $command without being connected"
             );
             return false;
         }
@@ -691,19 +685,19 @@ class SMTP
         $code = substr($reply, 0, 3);
 
         if ($this->do_debug >= 2) {
-            $this->edebug('SMTP -> FROM SERVER:' . $reply);
+            $this->edebug('SERVER -> CLIENT: ' . $reply);
         }
 
         if (!in_array($code, (array)$expect)) {
             $this->last_reply = null;
             $this->error = array(
-                "error" => "$command command failed",
-                "smtp_code" => $code,
-                "detail" => substr($reply, 4)
+                'error' => "$command command failed",
+                'smtp_code' => $code,
+                'detail' => substr($reply, 4)
             );
             if ($this->do_debug >= 1) {
                 $this->edebug(
-                    'SMTP -> ERROR: ' . $this->error['error'] . ': ' . $reply
+                    'SMTP ERROR: ' . $this->error['error'] . ': ' . $reply
                 );
             }
             return false;
@@ -729,7 +723,7 @@ class SMTP
      */
     public function sendAndMail($from)
     {
-        return $this->sendCommand("SAML", "SAML FROM:$from", 250);
+        return $this->sendCommand('SAML', "SAML FROM:$from", 250);
     }
 
     /**
@@ -740,7 +734,7 @@ class SMTP
      */
     public function verify($name)
     {
-        return $this->sendCommand("VRFY", "VRFY $name", array(250, 251));
+        return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
     }
 
     /**
@@ -751,14 +745,14 @@ class SMTP
      */
     public function noop()
     {
-        return $this->sendCommand("NOOP", "NOOP", 250);
+        return $this->sendCommand('NOOP', 'NOOP', 250);
     }
 
     /**
      * Send an SMTP TURN command.
      * This is an optional command for SMTP that this class does not support.
-     * This method is here to make the RFC821 Definition
-     * complete for this class and __may__ be implemented in future
+     * This method is here to make the RFC821 Definition complete for this class
+     * and _may_ be implemented in future
      * Implements from rfc 821: TURN <CRLF>
      * @access public
      * @return bool
@@ -769,7 +763,7 @@ class SMTP
             'error' => 'The SMTP TURN command is not implemented'
         );
         if ($this->do_debug >= 1) {
-            $this->edebug('SMTP -> NOTICE: ' . $this->error['error']);
+            $this->edebug('SMTP NOTICE: ' . $this->error['error']);
         }
         return false;
     }
@@ -778,12 +772,12 @@ class SMTP
      * Send raw data to the server.
      * @param string $data The data to send
      * @access public
-     * @return int|bool The number of bytes sent to the server or FALSE on error
+     * @return int|bool The number of bytes sent to the server or false on error
      */
     public function client_send($data)
     {
         if ($this->do_debug >= 1) {
-            $this->edebug("CLIENT -> SMTP: $data");
+            $this->edebug("CLIENT -> SERVER: $data");
         }
         return fwrite($this->smtp_conn, $data);
     }
@@ -819,12 +813,12 @@ class SMTP
      */
     protected function get_lines()
     {
-        $data = '';
-        $endtime = 0;
-        // If the connection is bad, give up now
+        // If the connection is bad, give up straight away
         if (!is_resource($this->smtp_conn)) {
-            return $data;
+            return '';
         }
+        $data = '';
+        $endtime = 0;
         stream_set_timeout($this->smtp_conn, $this->Timeout);
         if ($this->Timelimit > 0) {
             $endtime = time() + $this->Timelimit;
@@ -839,8 +833,8 @@ class SMTP
             if ($this->do_debug >= 4) {
                 $this->edebug("SMTP -> get_lines(): \$data is \"$data\"");
             }
-            // if 4th character is a space, we are done reading, break the loop
-            if (substr($str, 3, 1) == ' ') {
+            // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen
+            if ((isset($str[3]) and $str[3] == ' ')) {
                 break;
             }
             // Timed-out? Log and break
@@ -854,16 +848,14 @@ class SMTP
                 break;
             }
             // Now check if reads took too long
-            if ($endtime) {
-                if (time() > $endtime) {
-                    if ($this->do_debug >= 4) {
-                        $this->edebug(
-                            'SMTP -> get_lines(): timelimit reached ('
-                            . $this->Timelimit . ' sec)'
-                        );
-                    }
-                    break;
+            if ($endtime and time() > $endtime) {
+                if ($this->do_debug >= 4) {
+                    $this->edebug(
+                        'SMTP -> get_lines(): timelimit reached ('.
+                        $this->Timelimit . ' sec)'
+                    );
                 }
+                break;
             }
         }
         return $data;
