Beispiel #1
0
 /**
  * Try to authenticate using the username and password
  * Returns false on failure
  * @param string The username
  * @param string The password
  * @param Swift The instance of Swift this authenticator is used in
  * @return boolean
  */
 public function isAuthenticated($user, $pass, Swift $swift)
 {
   $log = Swift_LogContainer::getLog();
   if ($log->hasLevel(Swift_Log::LOG_EVERYTHING))
   {
     $log->add("Trying POP3 Before SMTP authentication.  Disconnecting from SMTP first.");
   }
   $swift->disconnect();
   try {
     $this->connection->start();
     $this->connection->assertOk($this->connection->read());
     $this->connection->write("USER " . $user);
     $this->connection->assertOk($this->connection->read());
     $this->connection->write("PASS " . $pass);
     $this->connection->assertOk($this->connection->read());
     $this->connection->write("QUIT");
     $this->connection->assertOk($this->connection->read());
     $this->connection->stop();
   } catch (Swift_ConnectionException $e) {
     if ($log->hasLevel(Swift_Log::LOG_ERRORS))
     {
       $log->add($e->getMessage(),Swift_Log::ERROR);
       $log->add("POP3 authentication failed.");
     }
     return false;
   }
   $options = $swift->getOptions();
   $swift->setOptions($options | Swift::NO_POST_CONNECT);
   $swift->connect();
   $swift->setOptions($options);
   return true;
 }
Beispiel #2
0
 /**
  * Constructor.
  * Creates the exception and appends log information if available.
  * @param string Message
  * @param int Code
  */
 public function __construct($message, $code = 0)
 {
     if (($log = Swift_LogContainer::getLog()) && $log->isEnabled()) {
         $message .= "<h3>Log Information</h3>";
         $message .= "<pre>" . htmlentities($log->dump(true)) . "</pre>";
     }
     parent::__construct($message, $code);
 }
 /**
  * Constructor
  * @param string The error message
  */
 function Swift_Exception($message)
 {
     if (($log =& Swift_LogContainer::getLog()) && $log->isEnabled()) {
         $message .= "<h3>Log Information</h3>";
         $message .= "<pre>" . htmlentities($log->dump(true)) . "</pre>";
     }
     $this->message = $message;
     $this->trace = debug_backtrace();
 }
 /**
  * Try to authenticate using the username and password
  * Returns false on failure
  * @param string The username
  * @param string The password
  * @param Swift The instance of Swift this authenticator is used in
  * @return boolean
  */
 function isAuthenticated($user, $pass, &$swift)
 {
     $log =& Swift_LogContainer::getLog();
     if ($log->hasLevel(SWIFT_LOG_EVERYTHING)) {
         $log->add("Trying POP3 Before SMTP authentication.  Disconnecting from SMTP first.");
     }
     $swift->disconnect();
     $this->connection->start();
     Swift_Errors::expect($e, "Swift_ConnectionException");
     if (!$e) {
         $this->connection->assertOk($this->connection->read());
     }
     if (!$e) {
         $this->connection->write("USER " . $user);
     }
     if (!$e) {
         $this->connection->assertOk($this->connection->read());
     }
     if (!$e) {
         $this->connection->write("PASS " . $pass);
     }
     if (!$e) {
         $this->connection->assertOk($this->connection->read());
     }
     if (!$e) {
         $this->connection->write("QUIT");
     }
     if (!$e) {
         $this->connection->assertOk($this->connection->read());
     }
     if (!$e) {
         $this->connection->stop();
     }
     if ($e) {
         if ($log->hasLevel(SWIFT_LOG_ERRORS)) {
             $log->add("POP3 authentication failed.");
         }
         return false;
     }
     Swift_Errors::clear("Swift_ConnectionException");
     $options = $swift->getOptions();
     $swift->setOptions($options | SWIFT_NO_POST_CONNECT);
     $swift->connect();
     $swift->setOptions($options);
     return true;
 }
Beispiel #5
0
 /**
  * Rotate to the next working connection
  * @throws Swift_ConnectionException If no connections are available
  */
 function nextConnection()
 {
     $log =& Swift_LogContainer::getLog();
     if ($log->hasLevel(SWIFT_LOG_EVERYTHING)) {
         $log->add(" <==> Rotating connection.");
     }
     $total = count($this->connections);
     $start = $this->active === null ? 0 : $this->active + 1;
     if ($start >= $total) {
         $start = 0;
     }
     $fail_messages = array();
     for ($id = $start; $id < $total; $id++) {
         if (in_array($id, $this->dead)) {
             continue;
         }
         //The connection was previously found to be useless
         Swift_Errors::expect($e, "Swift_ConnectionException");
         if (!$this->connections[$id]->isAlive()) {
             $this->connections[$id]->start();
         }
         if (!$e) {
             if ($this->connections[$id]->isAlive()) {
                 Swift_Errors::clear("Swift_ConnectionException");
                 $this->active = $id;
                 return true;
             }
             $this->dead[] = $id;
             $this->connections[$id]->stop();
             Swift_Errors::trigger(new Swift_ConnectionException("The connection started but reported that it was not active"));
         }
         $this->dead[] = $id;
         $this->connections[$id]->stop();
         $fail_messages[] = $id . ": " . $e->getMessage();
         $e = null;
     }
     $failure = implode("<br />", $fail_messages);
     Swift_Errors::trigger(new Swift_ConnectionException("No connections were started.<br />" . $failure));
 }
Beispiel #6
0
 /**
  * Try to start the connection
  * @throws Swift_ConnectionException Upon failure to start
  */
 public function start()
 {
     $log = Swift_LogContainer::getLog();
     $fail_messages = array();
     foreach ($this->connections as $id => $conn) {
         try {
             $this->connections[$id]->start();
             if ($this->connections[$id]->isAlive()) {
                 $this->active = $id;
                 return true;
             } else {
                 if ($log->hasLevel(Swift_Log::LOG_EVERYTHING)) {
                     $log->add("Connection (" . $id . ") failed. Will try next connection if available.");
                 }
                 throw new Swift_ConnectionException("The connection started but reported that it was not active");
             }
         } catch (Swift_ConnectionException $e) {
             $fail_messages[] = $id . ": " . $e->getMessage();
         }
     }
     $failure = implode("<br />", $fail_messages);
     throw new Swift_ConnectionException($failure);
 }
Beispiel #7
0
 /**
  * Rotate to the next working connection
  * @throws Swift_ConnectionException If no connections are available
  */
 public function nextConnection()
 {
     $log = Swift_LogContainer::getLog();
     if ($log->hasLevel(Swift_Log::LOG_EVERYTHING)) {
         $log->add(" <==> Rotating connection.");
     }
     $total = count($this->connections);
     $start = $this->active === null ? 0 : $this->active + 1;
     if ($start >= $total) {
         $start = 0;
     }
     $fail_messages = array();
     for ($id = $start; $id < $total; $id++) {
         if (in_array($id, $this->dead)) {
             continue;
         }
         //The connection was previously found to be useless
         try {
             if (!$this->connections[$id]->isAlive()) {
                 $this->connections[$id]->start();
             }
             if ($this->connections[$id]->isAlive()) {
                 $this->active = $id;
                 return true;
             } else {
                 $this->dead[] = $id;
                 $this->connections[$id]->stop();
                 throw new Swift_ConnectionException("The connection started but reported that it was not active");
             }
         } catch (Swift_ConnectionException $e) {
             $fail_messages[] = $id . ": " . $e->getMessage();
         }
     }
     $failure = implode("<br />", $fail_messages);
     throw new Swift_ConnectionException("No connections were started.<br />" . $failure);
 }
 /**
  * Set TRUE if the connection needs a EHLO greeting.
  * @param boolean
  */
 public function setRequiresEHLO($set)
 {
     $this->isESMTP = (bool) $set;
     $log = Swift_LogContainer::getLog();
     if ($log->hasLevel(Swift_Log::LOG_EVERYTHING)) {
         $log->add("Forcing ESMTP mode.  HELO is EHLO.");
     }
 }
Beispiel #9
0
 /**
  * Sends a message using the Swift mailer
  * @param Swift_Message $message The Swift message object
  * @param Swift_RecipientList $recipients The recipient list
  * @return int The number of messages sent successfully, else FALSE
  */
 private function send(Swift_Message $message, Swift_RecipientList $recipients)
 {
     if (gu_is_demo()) {
         return gu_error(t('Unable to send message in demo mode'));
     }
     try {
         $num_sent = $this->swift->send($message, $recipients, $this->from_address);
     } catch (Swift_ConnectionException $e) {
         gu_debug($e->getMessage());
         return gu_error(t('Unable to send message due to connection error'));
     }
     if (gu_is_debugging()) {
         $log =& Swift_LogContainer::getLog();
         gu_debug('gu_mailer::send(...)<br />' . nl2br(htmlspecialchars($log->dump(true))) . ' => ' . $num_sent);
         $log->clear();
     }
     return $num_sent;
 }
Beispiel #10
0
 function gmail(&$error, $to, $subject, $body, $fromName = "", $html = 0, $repto = "", $from = "", $cc = "", $reptoName = "")
 {
     global $errorReportingLevel;
     require_once GORUM_DIR . "/SwiftMailer/Swift.php";
     $_S =& new AppSettings();
     error_reporting(0);
     $log =& Swift_LogContainer::getLog();
     $log->setLogLevel($_S->swiftLog);
     Swift_Errors::expect($e, "Swift_Exception");
     if ($_S->smtpServer) {
         require_once GORUM_DIR . "/SwiftMailer/Swift/Connection/SMTP.php";
         if ($_S->fallBackNative) {
             require_once GORUM_DIR . "/SwiftMailer/Swift/Connection/NativeMail.php";
             require_once GORUM_DIR . "/SwiftMailer/Swift/Connection/Multi.php";
             $connections = array();
             $conn =& new Swift_Connection_SMTP($_S->smtpServer);
             $conn->setUsername($_S->smtpUser);
             $conn->setPassword($_S->smtpPass);
             $conn->setPort($_S->smtpPort);
             $conn->setPort($_S->smtpPort);
             $conn->setEncryption($_S->smtpSecure);
             if ($e !== null) {
                 $error = $e->getMessage();
                 return;
             }
             $connections[] =& $conn;
             // Fall back to native mail:
             $connections[] =& new Swift_Connection_NativeMail();
             if ($e !== null) {
                 $error = $e->getMessage();
                 return;
             }
             $swift =& new Swift(new Swift_Connection_Multi($connections));
         } else {
             $connection =& new Swift_Connection_SMTP($_S->smtpServer);
             $connection->setUsername($_S->smtpUser);
             $connection->setPassword($_S->smtpPass);
             $connection->setPort($_S->smtpPort);
             $connection->setEncryption($_S->smtpSecure);
             if ($e !== null) {
                 $error = $e->getMessage();
                 return;
             }
             $swift =& new Swift($connection);
         }
     } else {
         require_once GORUM_DIR . "/SwiftMailer/Swift/Connection/NativeMail.php";
         $swift =& new Swift(new Swift_Connection_NativeMail());
     }
     error_reporting($errorReportingLevel);
     if ($e !== null) {
         $error = $e->getMessage();
         return;
     } else {
         $error = "";
         Swift_Errors::clear("Swift_Exception");
     }
     $subject = str_replace(array("&lt;", "&gt;"), array("<", ">"), $subject);
     $charset = "utf-8";
     $message =& new Swift_Message($subject);
     $message->setCharset($charset);
     $part1 =& new Swift_Message_Part($body, "text/html");
     $part1->setCharset($charset);
     $message->attach($part1);
     $part2 =& new Swift_Message_Part(strip_tags($body));
     $part2->setCharset($charset);
     $message->attach($part2);
     if ($repto) {
         $message->setReplyTo(new Swift_Address($repto, $reptoName));
     }
     error_reporting(0);
     Swift_Errors::expect($e, "Swift_Exception");
     $recipients = new Swift_RecipientList();
     $recipients->addTo($to);
     if ($this->cc) {
         $recipients->addCc($this->cc);
     }
     $swift->send($message, $recipients, new Swift_Address($from, $fromName));
     if ($e !== null) {
         $error = $e->getMessage();
     } else {
         $error = "";
         Swift_Errors::clear("Swift_Exception");
     }
     $swift->disconnect();
     error_reporting($errorReportingLevel);
 }
Beispiel #11
0
 /**
  * Try to close the connection
  * @throws Swift_ConnectionException Upon failure to close
  */
 public function stop()
 {
     $log = Swift_LogContainer::getLog();
     if ($log->hasLevel(Swift_Log::LOG_EVERYTHING)) {
         $log->add("Closing down SMTP connection.");
     }
     if ($this->handle) {
         if (!fclose($this->handle)) {
             throw new Swift_ConnectionException("The SMTP connection could not be closed for an unknown reason." . $this->smtpErrors());
         }
         $this->handle = null;
     }
 }
Beispiel #12
0
 public function getLogDetails()
 {
     $swift = $this->getSwiftInstance();
     $log = Swift_LogContainer::getLog();
     return "<h3>Log Information</h3><pre>" . htmlentities($log->dump(true)) . "</pre>";
 }
 function SendEmail($to, $subject, $body, $task_id = null)
 {
     global $fs, $proj, $user;
     if (empty($to) || empty($to[0])) {
         return;
     }
     // Do we want to use a remote mail server?
     if (!empty($fs->prefs['smtp_server'])) {
         // connection... SSL, TLS or none
         if ($fs->prefs['email_tls']) {
             $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 587, 'tls');
         } else {
             if ($fs->prefs['email_ssl']) {
                 $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 465, 'ssl');
             } else {
                 $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server']);
             }
         }
         if ($fs->prefs['smtp_user']) {
             $swiftconn->setUsername($fs->prefs['smtp_user']);
             $swiftconn->setPassword($fs->prefs['smtp_pass']);
         }
         if (defined('FS_SMTP_TIMEOUT')) {
             $swiftconn->setTimeout(FS_SMTP_TIMEOUT);
         }
         // Use php's built-in mail() function
     } else {
         $swiftconn = Swift_MailTransport::newInstance();
     }
     if (defined('FS_MAIL_LOGFILE')) {
         $log = Swift_LogContainer::getLog();
         $log->setLogLevel(SWIFT_LOG_EVERYTHING);
     }
     $swift = Swift_Mailer::newInstance($swiftconn);
     $message = new Swift_Message($subject);
     $message->setBody($body);
     $type = $message->getHeaders()->get('Content-Type');
     $type->setValue('text/plain');
     $type->setParameter('charset', 'utf-8');
     $message->getHeaders()->addTextHeader('Precedence', 'list');
     $message->getHeaders()->addTextHeader('X-Mailer', 'Flyspray');
     if ($proj->prefs['notify_reply']) {
         $message->setReplyTo($proj->prefs['notify_reply']);
     }
     if (isset($task_id)) {
         $hostdata = parse_url($GLOBALS['baseurl']);
         $inreplyto = sprintf('<FS%d@%s>', $task_id, $hostdata['host']);
         // see http://cr.yp.to/immhf/thread.html this does not seems to work though :(
         $message->getHeaders()->addTextHeader('In-Reply-To', $inreplyto);
         $message->getHeaders()->addTextHeader('References', $inreplyto);
     }
     // now accepts string , array or Swift_Address.
     $message->setTo($to);
     $message->setFrom(array($fs->prefs['admin_email'] => $proj->prefs['project_title']));
     $swift->send($message);
     if (defined('FS_MAIL_LOGFILE')) {
         if (is_writable(dirname(FS_MAIL_LOGFILE))) {
             if ($fh = fopen(FS_MAIL_LOGFILE, 'ab')) {
                 fwrite($fh, $log->dump(true));
                 fwrite($fh, php_uname());
                 fclose($fh);
             }
         }
     }
     return true;
 }
Beispiel #14
0
 /**
  * Try to close the connection
  * @throws Swift_ConnectionException Upon failure to close
  */
 function stop()
 {
     $log =& Swift_LogContainer::getLog();
     if ($log->hasLevel(SWIFT_LOG_EVERYTHING)) {
         $log->add("Closing down SMTP connection.");
     }
     if ($this->handle) {
         if (!fclose($this->handle)) {
             Swift_Errors::trigger(new Swift_ConnectionException("The SMTP connection could not be closed for an unknown reason." . $this->smtpErrors()));
             return;
         }
         $this->handle = null;
     }
 }
Beispiel #15
0
 /**
  * Try to start the connection
  * @throws Swift_ConnectionException Upon failure to start
  */
 function start()
 {
     $log =& Swift_LogContainer::getLog();
     $fail_messages = array();
     foreach ($this->connections as $id => $conn) {
         Swift_Errors::expect($e, "Swift_ConnectionException");
         //
         $this->connections[$id]->start();
         if (!$e) {
             if ($this->connections[$id]->isAlive()) {
                 Swift_Errors::clear("Swift_ConnectionException");
                 $this->active = $id;
                 return true;
             }
             if ($log->hasLevel(SWIFT_LOG_EVERYTHING)) {
                 $log->add("Connection (" . $id . ") failed. Will try next connection if available.");
             }
             Swift_Errors::trigger(new Swift_ConnectionException("The connection started but reported that it was not active"));
         }
         $fail_messages[] = $id . ": " . $e->getMessage();
         $e = null;
     }
     $failure = implode("<br />", $fail_messages);
     Swift_Errors::trigger(new Swift_ConnectionException($failure));
 }
 /**
  * Get a list of any addresses which have failed since instantiation
  * @return array
  */
 public function getFailedRecipients()
 {
     $log = Swift_LogContainer::getLog();
     return $log->getFailedRecipients();
 }
Beispiel #17
0
 /**
  * Try to close the connection
  */
 public function stop()
 {
     $log = Swift_LogContainer::getLog();
     if ($log->hasLevel(Swift_Log::LOG_EVERYTHING)) {
         $log->add("Terminating sendmail process.");
     }
     foreach ((array) $this->pipes as $pipe) {
         @fclose($pipe);
     }
     if ($this->proc) {
         proc_close($this->proc);
         $this->pipes = null;
         $this->proc = null;
     }
 }
Beispiel #18
0
  /**
   * Write a command to the remote socket
   * @param string the command to send (without CRLF)
   * @throws Swift_ConnectionException If the command cannot be written
   */
  public function write($command)
  {
    if (false === fwrite($this->handle, $command . "\r\n"))
    {
      Swift_ClassLoader::load("Swift_ConnectionException");
      throw new Swift_ConnectionException("Data could not be written to the POP3 connection.");
    }

    $log = Swift_LogContainer::getLog();
    if ($log->hasLevel(Swift_Log::LOG_NETWORK))
    {
      $log->add($command,Swift_Log::COMMAND);
    }
  }
Beispiel #19
0
 /**
  * Email reset link to the user.
  *
  * @param the email address of the user requesting a password reset.
  * @param the username of the user requesting a password reset.
  * @param the new generated password.
  *
  * @return void.
  */
 private function _email_resetlink($email, $name, $secret_url)
 {
     $to = $email;
     $from = array(Kohana::config('settings.site_email'), Kohana::config('settings.site_name'));
     $subject = Kohana::lang('ui_admin.password_reset_subject');
     $message = $this->_email_resetlink_message($name, $secret_url);
     try {
         $recipients = email::send($to, $from, $subject, $message, FALSE);
     } catch (Exception $e) {
         Kohana::log('warning', Swift_LogContainer::getLog()->dump(true));
         return FALSE;
     }
     return TRUE;
 }
Beispiel #20
0
 /**
  * Handle the message send event and use SwiftMailer to mail
  */
 function handle_message_send(&$event, $param)
 {
     require_once dirname(__FILE__) . '/Swift.php';
     require_once dirname(__FILE__) . '/Swift/Connection/SMTP.php';
     $ok = false;
     if ($this->getConf('debug')) {
         $log =& Swift_LogContainer::getLog();
         $log->setLogLevel(Swift_Log::LOG_EVERYTHING);
     }
     try {
         // initialize the connection
         $smtp =& new Swift_Connection_SMTP($this->getConf('smtp_host'), $this->getConf('smtp_port'), $this->getConf('smtp_ssl'));
         // use Pop-before-SMTP
         if ($this->getConf('pop3_host')) {
             require_once dirname(__FILE__) . '/Swift/Authenticator/@PopB4Smtp.php';
             $smtp->attachAuthenticator(new Swift_Authenticator_PopB4Smtp($this->getConf('pop3_host')));
         }
         // use SMTP auth?
         if ($this->getConf('auth_user')) {
             $smtp->setUsername($this->getConf('auth_user'));
         }
         if ($this->getConf('auth_pass')) {
             $smtp->setPassword($this->getConf('auth_pass'));
         }
         // start Swift
         $swift =& new Swift($smtp, $this->getConf('localdomain'));
         // did we get an Adora Belle Mailer object?
         if (isset($event->data['mail']) && is_a($event->data['mail'], 'Mailer')) {
             // we'd need to call cleanHeaders() here, but it's protected in Adora Belle.
             // instead we call the dump() method which will call cleanHeaders for us
             if (is_callable(array($event->data['mail'], 'cleanHeaders()'))) {
                 $event->data['mail']->cleanHeaders();
             } else {
                 $event->data['mail']->dump();
             }
         }
         // prepare message (Swift autodetects UTF-8)
         $message =& new Swift_Message($event->data['subject'], $event->data['body']);
         // handle the recipients (duplicates some code from mail_encode_address)
         $reci =& new Swift_RecipientList();
         $from = null;
         $num = 0;
         foreach (array('to', 'cc', 'bcc', 'from') as $hdr) {
             $parts = explode(',', $event->data[$hdr]);
             foreach ($parts as $part) {
                 $part = trim($part);
                 // parse address
                 if (preg_match('#(.*?)<(.*?)>#', $part, $matches)) {
                     $text = trim($matches[1]);
                     $addr = $matches[2];
                 } else {
                     $addr = $part;
                 }
                 // skip empty ones
                 if (empty($addr)) {
                     continue;
                 }
                 // add
                 if ($hdr == 'from') {
                     $from =& new Swift_Address($addr, $text);
                 } else {
                     if ($hdr == 'to' || $hdr == 'cc') {
                         $num++;
                     }
                     if ($hdr == 'bcc' && $num == 0) {
                         // no to and cc - add bcc as to and send as batch later
                         $reci->add($addr, $text, 'to');
                     } else {
                         $reci->add($addr, $text, $hdr);
                     }
                 }
             }
         }
         // now finally send the mail
         if ($num) {
             $ok = $swift->send($message, $reci, $from);
         } else {
             $ok = $swift->batchSend($message, $reci, $from);
         }
     } catch (Swift_ConnectionException $e) {
         msg('There was a problem communicating with SMTP: ' . $e->getMessage(), -1);
     } catch (Swift_Message_MimeException $e) {
         msg('There was an unexpected problem building the email: ' . $e->getMessage(), -1);
     } catch (Exception $e) {
         msg('There was an unexpected problem with sending the email: ' . $e->getMessage(), -1);
     }
     if (!$ok && $this->getConf('debug')) {
         $dbglog = $log->dump(true);
         $dbglog = preg_replace('/(AUTH \\w+ ).*$/m', '\\1 ***', $dbglog);
         //filter out passwords
         $dbglog = preg_replace('/(PASS ).*$/m', '\\1 ***', $dbglog);
         //filter out passwords
         msg('SwiftMailer log:<br /><pre>' . hsc($dbglog) . '</pre>', -1);
     }
     $event->preventDefault();
     $event->stopPropagation();
     $event->result = $ok;
     $event->data['success'] = $ok;
 }
Beispiel #21
0
 /**
  * Send a message to any number of recipients
  * @param Swift_Message The message to send.  This does not need to (and shouldn't really) have any of the recipient headers set.
  * @param mixed The recipients to send to.  Can be a string, Swift_Address or Swift_RecipientList. Note that all addresses apart from Bcc recipients will appear in the message headers
  * @param mixed The address to send the message from.  Can either be a string or an instance of Swift_Address.
  * @return int The number of successful recipients
  * @throws Swift_ConnectionException If sending fails for any reason.
  */
 public function send(Swift_Message $message, $recipients, $from)
 {
     Swift_ClassLoader::load("Swift_Message_Encoder");
     if (is_string($recipients) && preg_match("/^" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . "\$/", $recipients)) {
         $recipients = new Swift_Address($recipients);
     } elseif (!$recipients instanceof Swift_AddressContainer) {
         throw new Exception("The recipients parameter must either be a valid string email address, " . "an instance of Swift_RecipientList or an instance of Swift_Address.");
     }
     if (is_string($from) && preg_match("/^" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . "\$/", $from)) {
         $from = new Swift_Address($from);
     } elseif (!$from instanceof Swift_Address) {
         throw new Exception("The sender parameter must either be a valid string email address or " . "an instance of Swift_Address.");
     }
     $log = Swift_LogContainer::getLog();
     if (!$message->getEncoding() && !$this->connection->hasExtension("8BITMIME")) {
         $message->setEncoding("QP", true, true);
     }
     $list = $recipients;
     if ($recipients instanceof Swift_Address) {
         $list = new Swift_RecipientList();
         $list->addTo($recipients);
     }
     Swift_ClassLoader::load("Swift_Events_SendEvent");
     $send_event = new Swift_Events_SendEvent($message, $list, $from, 0);
     $this->notifyListeners($send_event, "BeforeSendListener");
     $to = $cc = array();
     if (!($has_from = $message->getFrom())) {
         $message->setFrom($from);
     }
     if (!($has_return_path = $message->getReturnPath())) {
         $message->setReturnPath($from->build(true));
     }
     if (!($has_reply_to = $message->getReplyTo())) {
         $message->setReplyTo($from);
     }
     if (!$has_reply_to[0]) {
         $message->setReplyTo($from->getAddress());
     }
     if (!($has_message_id = $message->getId())) {
         $message->generateId();
     }
     $this->command("MAIL FROM: " . $message->getReturnPath(true), 250);
     $failed = 0;
     $sent = 0;
     $tmp_sent = 0;
     $it = $list->getIterator("to");
     while ($it->hasNext()) {
         $it->next();
         $address = $it->getValue();
         $to[] = $address->build();
         try {
             $this->command("RCPT TO: " . $address->build(true), 250);
             $tmp_sent++;
         } catch (Swift_BadResponseException $e) {
             $failed++;
             $send_event->addFailedRecipient($address->getAddress());
             if ($log->hasLevel(Swift_Log::LOG_FAILURES)) {
                 $log->addfailedRecipient($address->getAddress());
             }
         }
     }
     $it = $list->getIterator("cc");
     while ($it->hasNext()) {
         $it->next();
         $address = $it->getValue();
         $cc[] = $address->build();
         try {
             $this->command("RCPT TO: " . $address->build(true), 250);
             $tmp_sent++;
         } catch (Swift_BadResponseException $e) {
             $failed++;
             $send_event->addFailedRecipient($address->getAddress());
             if ($log->hasLevel(Swift_Log::LOG_FAILURES)) {
                 $log->addfailedRecipient($address->getAddress());
             }
         }
     }
     if ($failed == count($to) + count($cc)) {
         $this->reset();
         $this->notifyListeners($send_event, "SendListener");
         return 0;
     }
     if (!($has_to = $message->getTo()) && !empty($to)) {
         $message->setTo($to);
     }
     if (!($has_cc = $message->getCc()) && !empty($cc)) {
         $message->setCc($cc);
     }
     $this->command("DATA", 354);
     $data = $message->build();
     while (false !== ($bytes = $data->read())) {
         $this->command($bytes, -1);
     }
     if ($log->hasLevel(Swift_Log::LOG_NETWORK)) {
         $log->add("<MESSAGE DATA>", Swift_Log::COMMAND);
     }
     try {
         $this->command("\r\n.", 250);
         $sent += $tmp_sent;
     } catch (Swift_BadResponseException $e) {
         $failed += $tmp_sent;
     }
     $tmp_sent = 0;
     $has_bcc = $message->getBcc();
     $it = $list->getIterator("bcc");
     while ($it->hasNext()) {
         $it->next();
         $address = $it->getValue();
         if (!$has_bcc) {
             $message->setBcc($address->build());
         }
         try {
             $this->command("MAIL FROM: " . $message->getReturnPath(true), 250);
             $this->command("RCPT TO: " . $address->build(true), 250);
             $this->command("DATA", 354);
             $data = $message->build();
             while (false !== ($bytes = $data->read())) {
                 $this->command($bytes, -1);
             }
             if ($log->hasLevel(Swift_Log::LOG_NETWORK)) {
                 $log->add("<MESSAGE DATA>", Swift_Log::COMMAND);
             }
             $this->command("\r\n.", 250);
             $sent++;
         } catch (Swift_BadResponseException $e) {
             $failed++;
             $send_event->addFailedRecipient($address->getAddress());
             if ($log->hasLevel(Swift_Log::LOG_FAILURES)) {
                 $log->addfailedRecipient($address->getAddress());
             }
             $this->reset();
         }
     }
     $total = count($to) + count($cc) + count($list->getBcc());
     $send_event->setNumSent($sent);
     $this->notifyListeners($send_event, "SendListener");
     if (!$has_return_path) {
         $message->setReturnPath("");
     }
     if (!$has_from) {
         $message->setFrom("");
     }
     if (!$has_to) {
         $message->setTo("");
     }
     if (!$has_reply_to) {
         $message->setReplyTo(null);
     }
     if (!$has_cc) {
         $message->setCc(null);
     }
     if (!$has_bcc) {
         $message->setBcc(null);
     }
     if (!$has_message_id) {
         $message->setId(null);
     }
     if ($log->hasLevel(Swift_Log::LOG_NETWORK)) {
         $log->add("Message sent to " . $sent . "/" . $total . " recipients", Swift_Log::NORMAL);
     }
     return $sent;
 }
 public function testFailedRecipientsAreReturned()
 {
     $conn = new FullMockConnection();
     $conn->setReturnValueAt(0, "read", "220 xxx ESMTP");
     $conn->setReturnValueAt(1, "read", "250-Hello xxx\r\n250 HELP");
     $conn->setReturnValueAt(2, "read", "250 Ok");
     $conn->setReturnValueAt(3, "read", "550 Denied");
     $conn->setReturnValueAt(4, "read", "250 ok");
     $conn->setReturnValueAt(5, "read", "550 Denied");
     $conn->setReturnValueAt(6, "read", "354 Go ahead");
     $conn->setReturnValueAt(7, "read", "250 ok");
     $log = Swift_LogContainer::getLog();
     $swift = new Swift($conn, "abc", Swift::ENABLE_LOGGING);
     $message = new Swift_Message("My Subject", "my body");
     $recipients = new Swift_RecipientList();
     $recipients->addTo("*****@*****.**", "XXX YYY");
     $recipients->addTo("*****@*****.**");
     $recipients->addCc("*****@*****.**");
     $this->assertEqual(1, $swift->send($message, $recipients, new Swift_Address("*****@*****.**", "Foo Bar")));
     $this->assertEqual(array("*****@*****.**", "*****@*****.**"), $log->getFailedRecipients());
 }