示例#1
0
 /**
  * Sends messages using the given transport instance.
  *
  * @param \Swift_Transport $transport         A transport instance
  * @param string[]        &$failedRecipients  An array of failures by-reference
  *
  * @return int The number of sent emails
  */
 public function flushQueue(\Swift_Transport $transport, &$failedRecipients = null)
 {
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $repo = $this->em->getRepository($this->entityClass);
     $limit = $this->getMessageLimit();
     $limit = $limit > 0 ? $limit : null;
     $emails = $repo->findBy(array("status" => self::STATUS_READY), null, $limit);
     if (!count($emails)) {
         return 0;
     }
     $failedRecipients = (array) $failedRecipients;
     $count = 0;
     $time = time();
     /** @var SpoolItem $email */
     foreach ($emails as $email) {
         $email->setStatus(self::STATUS_PROCESSING);
         $this->em->persist($email);
         $this->em->flush();
         /** @var \Swift_Message $message */
         $message = unserialize($email->getMessage());
         $count += $transport->send($message, $failedRecipients);
         $this->em->remove($email);
         $this->em->flush();
         if ($this->getTimeLimit() && time() - $time >= $this->getTimeLimit()) {
             break;
         }
     }
     return $count;
 }
示例#2
0
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     foreach ($this->messages as $message) {
         $transport->send($message);
     }
     $this->messages = array();
 }
示例#3
0
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport        A transport instance
  * @param string[]        $failedRecipients An array of failures by-reference
  *
  * @return int The number of sent emails
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     if (!$this->messages) {
         return 0;
     }
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $count = 0;
     $retries = $this->flushRetries;
     while ($retries--) {
         try {
             while ($message = array_pop($this->messages)) {
                 $count += $transport->send($message, $failedRecipients);
             }
         } catch (Swift_TransportException $exception) {
             if ($retries) {
                 // re-queue the message at the end of the queue to give a chance
                 // to the other messages to be sent, in case the failure was due to
                 // this message and not just the transport failing
                 array_unshift($this->messages, $message);
                 // wait half a second before we try again
                 usleep(500000);
             } else {
                 throw $exception;
             }
         }
     }
     return $count;
 }
示例#4
0
文件: FileSpool.php 项目: hunde/bsc
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport         A transport instance
  * @param string[]        &$failedRecipients An array of failures by-reference
  *
  * @return int The number of sent emails
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $failedRecipients = (array) $failedRecipients;
     $count = 0;
     $time = time();
     foreach (new DirectoryIterator($this->_path) as $file) {
         $file = $file->getRealPath();
         if (!strpos($file, '.message')) {
             continue;
         }
         $message = unserialize(file_get_contents($file));
         $count += $transport->send($message, $failedRecipients);
         unlink($file);
         if ($this->getMessageLimit() && $count >= $this->getMessageLimit()) {
             break;
         }
         if ($this->getTimeLimit() && time() - $time >= $this->getTimeLimit()) {
             break;
         }
     }
     return $count;
 }
示例#5
0
 function __construct(LoggerInterface $logger, \Swift_Transport $transport)
 {
     $this->logger = $logger;
     // We register the plugin here and not using the swiftmailer.plugin tag
     // to avoid the ServiceCircularReferenceException we get when Monolog is
     // configured to mail the messages through SwiftMailer.
     $transport->registerPlugin(new \Swift_Plugins_LoggerPlugin($this));
 }
示例#6
0
    /**
     * Prepares a transport using the TYPO3_CONF_VARS configuration
     *
     * Used options:
     * $TYPO3_CONF_VARS['MAIL']['transport'] = 'smtp' | 'sendmail' | 'mail' | 'mbox'
     *
     * $TYPO3_CONF_VARS['MAIL']['transport_smtp_server'] = 'smtp.example.org';
     * $TYPO3_CONF_VARS['MAIL']['transport_smtp_port'] = '25';
     * $TYPO3_CONF_VARS['MAIL']['transport_smtp_encrypt'] = FALSE; # requires openssl in PHP
     * $TYPO3_CONF_VARS['MAIL']['transport_smtp_username'] = '******';
     * $TYPO3_CONF_VARS['MAIL']['transport_smtp_password'] = '******';
     *
     * $TYPO3_CONF_VARS['MAIL']['transport_sendmail_command'] = '/usr/sbin/sendmail -bs'
     *
     * @throws \TYPO3\CMS\Core\Exception
     * @throws RuntimeException
     */
    private function initializeTransport()
    {
        switch ($this->mailSettings['transport']) {
            case 'smtp':
                // Get settings to be used when constructing the transport object
                list($host, $port) = preg_split('/:/', $this->mailSettings['transport_smtp_server']);
                if ($host === '') {
                    throw new \TYPO3\CMS\Core\Exception('$TYPO3_CONF_VARS[\'MAIL\'][\'transport_smtp_server\'] needs to be set when transport is set to "smtp"', 1291068606);
                }
                if ($port === '') {
                    $port = '25';
                }
                $useEncryption = $this->mailSettings['transport_smtp_encrypt'] ? $this->mailSettings['transport_smtp_encrypt'] : NULL;
                // Create our transport
                $this->transport = \Swift_SmtpTransport::newInstance($host, $port, $useEncryption);
                // Need authentication?
                $username = $this->mailSettings['transport_smtp_username'];
                if ($username !== '') {
                    $this->transport->setUsername($username);
                }
                $password = $this->mailSettings['transport_smtp_password'];
                if ($password !== '') {
                    $this->transport->setPassword($password);
                }
                break;
            case 'sendmail':
                $sendmailCommand = $this->mailSettings['transport_sendmail_command'];
                if (empty($sendmailCommand)) {
                    throw new \TYPO3\CMS\Core\Exception('$TYPO3_CONF_VARS[\'MAIL\'][\'transport_sendmail_command\'] needs to be set when transport is set to "sendmail"', 1291068620);
                }
                // Create our transport
                $this->transport = \Swift_SendmailTransport::newInstance($sendmailCommand);
                break;
            case 'mbox':
                $mboxFile = $this->mailSettings['transport_mbox_file'];
                if ($mboxFile == '') {
                    throw new \TYPO3\CMS\Core\Exception('$TYPO3_CONF_VARS[\'MAIL\'][\'transport_mbox_file\'] needs to be set when transport is set to "mbox"', 1294586645);
                }
                // Create our transport
                $this->transport = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MboxTransport', $mboxFile);
                break;
            case 'mail':
                // Create the transport, no configuration required
                $this->transport = \Swift_MailTransport::newInstance();
                break;
            default:
                // Custom mail transport
                $customTransport = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($this->mailSettings['transport'], $this->mailSettings);
                if ($customTransport instanceof \Swift_Transport) {
                    $this->transport = $customTransport;
                } else {
                    throw new \RuntimeException($this->mailSettings['transport'] . ' is not an implementation of \\Swift_Transport,
						but must implement that interface to be used as a mail transport.', 1323006478);
                }
        }
        return;
    }
 public function postTask(Worker $worker, array $options = null)
 {
     if ($worker instanceof MailerAwareWorker) {
         if ($this->mailer && $this->transport) {
             //Flush the mailer queue, this isn't normally done until the command execution finishes
             $this->mailer->getTransport()->getSpool()->flushQueue($this->transport);
             $this->transport->stop();
             $this->logger->info('Flushed mail queue');
         }
     }
 }
示例#8
0
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport         A transport instance
  * @param string[]        &$failedRecipients An array of failures by-reference
  *
  * @return int The number of sent emails
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $count = 0;
     while ($message = array_pop($this->messages)) {
         $count += $transport->send($message, $failedRecipients);
     }
     return $count;
 }
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport        A transport instance
  * @param string[]        $failedRecipients An array of failures by-reference
  * @return int The number of sent e-mails
  * @throws Swift_IoException
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $limit = $this->getMessageLimit();
     $results = $this->collection->find(array('sentOn' => null));
     if ($limit > 0) {
         $results->limit($limit);
     }
     $failedRecipients = (array) $failedRecipients;
     $count = 0;
     $time = time();
     $timeLimit = $this->getTimeLimit();
     foreach ($results as $result) {
         if (!isset($result['message']) || !$result['message'] instanceof \MongoBinData) {
             continue;
         }
         $id = $result['_id'];
         $this->write(array('_id' => $id), array('$set' => array('sentOn' => new \MongoDate())));
         $message = unserialize($result['message']->bin);
         $count += $transport->send($message, $failedRecipients);
         try {
             $this->collection->remove(array('_id' => $id));
         } catch (\Exception $e) {
             throw new Swift_IoException("Could not update email sent on date", 0, $e);
         }
         if ($timeLimit && time() - $time >= $timeLimit) {
             break;
         }
     }
     return $count;
 }
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport         A transport instance
  * @param string[]        &$failedRecipients An array of failures by-reference
  *
  * @return int The number of sent emails
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     $criteria = new Criteria();
     $criteria->setLimit($this->getMessageLimit());
     $model = constant($this->model . '::PEER');
     $objects = call_user_func(array($model, $this->method), $criteria);
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $method = 'get' . call_user_func(array($model, 'translateFieldName'), $this->column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
     $count = 0;
     $time = time();
     foreach ($objects as $object) {
         if (is_resource($object->getMessage())) {
             $message = unserialize(stream_get_contents($object->getMessage()));
         } else {
             $message = unserialize($object->getMessage());
         }
         $object->delete();
         try {
             $count += $transport->send($message, $failedRecipients);
         } catch (Exception $e) {
             // TODO: What to do with errors?
         }
         if ($this->getTimeLimit() && time() - $time >= $this->getTimeLimit()) {
             break;
         }
     }
     return $count;
 }
 private function recoverSpool($name, \Swift_Transport $transport, InputInterface $input, OutputInterface $output)
 {
     if ($transport instanceof \Swift_Transport_SpoolTransport) {
         $spool = $transport->getSpool();
         if ($spool instanceof \Swift_ConfigurableSpool) {
             $spool->setMessageLimit($input->getOption('message-limit'));
             $spool->setTimeLimit($input->getOption('time-limit'));
         }
         if ($spool instanceof \Swift_FileSpool) {
             if (null !== $input->getOption('recover-timeout')) {
                 $spool->recover($input->getOption('recover-timeout'));
             } else {
                 $spool->recover();
             }
         }
         $transportService = $input->getOption('transport') ?: sprintf('swiftmailer.mailer.%s.transport.real', $name);
         $sent = $spool->flushQueue($this->getContainer()->get($transportService));
         $this->io->text(sprintf('<comment>%d</comment> emails sent', $sent));
     }
 }
示例#12
0
 /**
  * {@inheritdoc}
  */
 public function flushQueue(\Swift_Transport $transport, &$failedRecipients = null)
 {
     if (!$this->redis->llen($this->key)) {
         return 0;
     }
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $failedRecipients = (array) $failedRecipients;
     $count = 0;
     $time = time();
     while ($message = unserialize($this->redis->lpop($this->key))) {
         $count += $transport->send($message, $failedRecipients);
         if ($this->getMessageLimit() && $count >= $this->getMessageLimit()) {
             break;
         }
         if ($this->getTimeLimit() && time() - $time >= $this->getTimeLimit()) {
             break;
         }
     }
     return $count;
 }
 /**
  * Prepares a transport using the TYPO3_CONF_VARS configuration
  *
  * Used options:
  * $TYPO3_CONF_VARS['MAIL']['transport'] = 'smtp' | 'sendmail' | 'mail' | 'mbox'
  *
  * $TYPO3_CONF_VARS['MAIL']['transport_smtp_server'] = 'smtp.example.org';
  * $TYPO3_CONF_VARS['MAIL']['transport_smtp_port'] = '25';
  * $TYPO3_CONF_VARS['MAIL']['transport_smtp_encrypt'] = FALSE; # requires openssl in PHP
  * $TYPO3_CONF_VARS['MAIL']['transport_smtp_username'] = '******';
  * $TYPO3_CONF_VARS['MAIL']['transport_smtp_password'] = '******';
  *
  * $TYPO3_CONF_VARS['MAIL']['transport_sendmail_command'] = '/usr/sbin/sendmail -bs'
  *
  * @throws t3lib_exception
  */
 private function initializeTransport()
 {
     $mailSettings = $GLOBALS['TYPO3_CONF_VARS']['MAIL'];
     switch ($mailSettings['transport']) {
         case 'smtp':
             // Get settings to be used when constructing the transport object
             list($host, $port) = preg_split('/:/', $mailSettings['transport_smtp_server']);
             if ($host === '') {
                 throw new t3lib_exception('$TYPO3_CONF_VARS[\'MAIL\'][\'transport_smtp_server\'] needs to be set when transport is set to "smtp"', 1291068606);
             }
             if ($port === '') {
                 $port = '25';
             }
             $useEncryption = $mailSettings['transport_smtp_encrypt'] ? TRUE : FALSE;
             // Create our transport
             $this->transport = Swift_SmtpTransport::newInstance($host, $port, $useEncryption);
             // Need authentication?
             $username = $mailSettings['transport_smtp_username'];
             if ($username !== '') {
                 $this->transport->setUsername($username);
             }
             $password = $mailSettings['transport_smtp_password'];
             if ($password !== '') {
                 $this->transport->setPassword($password);
             }
             break;
         case 'sendmail':
             $sendmailCommand = $mailSettings['transport_sendmail_command'];
             if ($sendmailCommand === '') {
                 throw new t3lib_exception('$TYPO3_CONF_VARS[\'MAIL\'][\'transport_sendmail_command\'] needs to be set when transport is set to "sendmail"', 1291068620);
             }
             // Create our transport
             $this->transport = Swift_SendmailTransport::newInstance($sendmailCommand);
             break;
         case 'mbox':
             $mboxFile = $mailSettings['transport_mbox_file'];
             if ($mboxFile == '') {
                 throw new t3lib_exception('$TYPO3_CONF_VARS[\'MAIL\'][\'transport_mbox_file\'] needs to be set when transport is set to "mbox"');
             }
             // Create our transport
             $this->transport = t3lib_div::makeInstance('t3lib_mail_mboxtransport', $mboxFile);
             break;
         case 'mail':
         default:
             // Create the transport, no configuration required
             $this->transport = Swift_MailTransport::newInstance();
             break;
     }
     return;
 }
示例#14
0
 /**
  * @internal
  * @return null|\Swift_Mailer
  */
 protected function getMailer()
 {
     if (!$this->enabled()) {
         return null;
     }
     if (!$this->mailer) {
         /** @var Config $config */
         $config = self::getGrav()['config'];
         $mailer = $config->get('plugins.email.mailer.engine');
         // Create the Transport and initialize it.
         switch ($mailer) {
             case 'smtp':
                 $transport = \Swift_SmtpTransport::newInstance();
                 $options = $config->get('plugins.email.mailer.smtp');
                 if (!empty($options['server'])) {
                     $transport->setHost($options['server']);
                 }
                 if (!empty($options['port'])) {
                     $transport->setPort($options['port']);
                 }
                 if (!empty($options['encryption']) && $options['encryption'] != 'none') {
                     $transport->setEncryption($options['encryption']);
                 }
                 if (!empty($options['user'])) {
                     $transport->setUsername($options['user']);
                 }
                 if (!empty($options['password'])) {
                     $transport->setPassword($options['password']);
                 }
                 break;
             case 'sendmail':
                 $options = $config->get('plugins.email.mailer.sendmail');
                 $bin = !empty($options['bin']) ? $options['bin'] : '/usr/sbin/sendmail';
                 $transport = \Swift_SendmailTransport::newInstance($bin);
                 break;
             case 'mail':
             default:
                 $transport = \Swift_MailTransport::newInstance();
         }
         // Create the Mailer using your created Transport
         $this->mailer = \Swift_Mailer::newInstance($transport);
         // Register the logger if we're debugging.
         if ($this->debug()) {
             $this->logger = new \Swift_Plugins_Loggers_ArrayLogger();
             $this->mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($this->logger));
         }
     }
     return $this->mailer;
 }
示例#15
0
 /**
  * Set transport
  *
  * @param string $type
  * @param array $options
  * @return Omnimessage\Service\Email
  */
 public function setTransport($type = 'smtp', $options = array())
 {
     if (!in_array($type, array_keys(self::$transports))) {
         throw new Exception('Email Transport: ' . $type . ' is not available');
     }
     switch ($type) {
         case 'smtp':
             $class = '\\' . self::$transports['smtp'];
             if (!isset($options['host']) && !isset($options['port'])) {
                 throw new Exception('Email Transport smtp requires host & port options');
             }
             $this->transport = $class::newInstance($options['host'], $options['port']);
             if (isset($options['username']) && isset($options['password'])) {
                 $this->transport->setUsername($options['username'])->setPassword($options['password']);
             }
             if (isset($options['encryption']) && in_array($options['encryption'], array('ssl', 'tls'))) {
                 $this->transport->setEncryption($options['encryption']);
             }
             break;
         case 'send_mail':
             $class = '\\' . self::$transports['send_mail'];
             $cmd = '/usr/sbin/sendmail -bs';
             if (!empty($options['cmd'])) {
                 $cmd = $options['cmd'];
             }
             $this->transport = $class::newInstance($cmd);
             break;
         case 'mail':
             $class = '\\' . self::$transports['mail'];
             $this->transport = $class::newInstance();
             break;
         default:
             throw new Exception('Email transport: ' . $type . ' is not supported');
     }
     return $this;
 }
  /**
   * Sends messages using the given transport instance.
   *
   * @param Swift_Transport $transport         A transport instance
   * @param string[]        &$failedRecipients An array of failures by-reference
   *
   * @return int The number of sent emails
   */
  public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
  {
    $queryMethod = $this->method;
    $model = constant($this->model.'::PEER');
    $modelQuery = PropelQuery::from($this->model);
    $objects = $modelQuery->$queryMethod()->limit($this->getMessageLimit())->find();
    
    if (!$transport->isStarted())
    {
      $transport->start();
    }

    $method = 'get'.call_user_func(array($model, 'translateFieldName'), $this->column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
    $count = 0;
    $time = time();
    foreach ($objects as $object)
    {
      $message = unserialize($object->$method());
      try
      {
        $count += $transport->send($message, $failedRecipients);
        $object->mailSent();
      }
      catch (Exception $e)
      {
        $object->mailUnsent();
      }

      if ($this->getTimeLimit() && (time() - $time) >= $this->getTimeLimit())
      {
        break;
      }
    }

    return $count;
  }
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport         A transport instance
  * @param string[]        &$failedRecipients An array of failures by-reference
  *
  * @return int The number of sent emails
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     $table = Doctrine_Core::getTable($this->model);
     $objects = $this->method ? $table->{$this->method}() : $table->createQuery()->execute();
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $count = 0;
     foreach ($objects as $object) {
         $message = unserialize($object->{$this->column});
         $object->delete();
         try {
             $count += $transport->send($message, $failedRecipients);
         } catch (Exception $e) {
             // TODO: What to do with errors?
         }
     }
     return $count;
 }
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport         A transport instance
  * @param string[]        &$failedRecipients An array of failures by-reference
  *
  * @return int The number of sent emails
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     $model = constant($this->model . '::PEER');
     $objects = $this->method ? call_user_func(array($model, $this->method)) : call_user_func(array($model, 'doSelect'), new Criteria());
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $method = 'get' . call_user_func(array($model, 'translateFieldName'), $this->column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
     $count = 0;
     foreach ($objects as $object) {
         $message = unserialize($object->{$method}());
         $object->delete();
         try {
             $count += $transport->send($message, $failedRecipients);
         } catch (Exception $e) {
             // TODO: What to do with errors?
         }
     }
     return $count;
 }
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport        A transport instance
  * @param string[]        $failedRecipients An array of failures by-reference
  * @throws Swift_IoException
  * @return int The number of sent e-mails
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $limit = $this->getMessageLimit();
     $results = $this->find(array('sentOn' => null), $limit > 0 ? array('limit' => $limit) : array());
     $failedRecipients = (array) $failedRecipients;
     $count = 0;
     $time = time();
     $timeLimit = $this->getTimeLimit();
     foreach ($results as $result) {
         if (!isset($result->message) || !$result->message instanceof \MongoDB\BSON\Binary) {
             continue;
         }
         $id = $result->_id;
         $this->setSentOn($id, $this->now());
         $count += $transport->send(unserialize($result->message->getData()), $failedRecipients);
         $this->delete($id);
         if ($timeLimit && time() - $time >= $timeLimit) {
             break;
         }
     }
     return $count;
 }
示例#20
0
文件: FileSpool.php 项目: saj696/pipe
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport A transport instance
  * @param string[] $failedRecipients An array of failures by-reference
  *
  * @return int The number of sent e-mail's
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     $directoryIterator = new DirectoryIterator($this->_path);
     /* Start the transport only if there are queued files to send */
     if (!$transport->isStarted()) {
         foreach ($directoryIterator as $file) {
             if (substr($file->getRealPath(), -8) == '.message') {
                 $transport->start();
                 break;
             }
         }
     }
     $failedRecipients = (array) $failedRecipients;
     $count = 0;
     $time = time();
     foreach ($directoryIterator as $file) {
         $file = $file->getRealPath();
         if (substr($file, -8) != '.message') {
             continue;
         }
         /* We try a rename, it's an atomic operation, and avoid locking the file */
         if (rename($file, $file . '.sending')) {
             $message = unserialize(file_get_contents($file . '.sending'));
             $count += $transport->send($message, $failedRecipients);
             unlink($file . '.sending');
         } else {
             /* This message has just been catched by another process */
             continue;
         }
         if ($this->getMessageLimit() && $count >= $this->getMessageLimit()) {
             break;
         }
         if ($this->getTimeLimit() && time() - $time >= $this->getTimeLimit()) {
             break;
         }
     }
     return $count;
 }
 /**
  * Send the mail
  * @param string|array $to - mail reciver, can be also as array('*****@*****.**' => 'John Doe')
  * @param enum(html|text) $format - format of letter (html or text)
  * @return boolean
  */
 public function send($to, $format = 'text')
 {
     //include_once LIBPATH
     rad_mailtemplate::setCurrentItem($this);
     $o = rad_rsmarty::getSmartyObject();
     if ($this->getVars()) {
         foreach ($this->getVars() as $key => $value) {
             $o->assign($key, $value);
         }
     }
     if (!is_file(MAILTEMPLATESPATH . $this->getTemplateName())) {
         throw new rad_exception('File "' . MAILTEMPLATESPATH . $this->getTemplateName() . '" not found!');
     }
     $o->fetch(MAILTEMPLATESPATH . $this->getTemplateName());
     $o->clearAllAssign();
     if (empty($this->_blocks[$format])) {
         throw new rad_exception('Format "' . $format . '" is not declared in file: "' . MAILTEMPLATESPATH . $this->getTemplateName() . '"');
     }
     if (!empty($this->_mailer)) {
         $this->_mailer->setSubject($this->_blocks[$format]['subject']);
         if (!empty($this->_blocks[$format]['Cc'])) {
             $this->_mailer->setCc($this->_blocks[$format]['Cc']);
         }
         if (!empty($this->_blocks[$format]['Bcc'])) {
             $this->_mailer->setBcc($this->_blocks[$format]['Bcc']);
         }
         if (!empty($this->_blocks[$format]['headers'])) {
             $headers = rad_mailtemplate::parseHeader($this->_blocks[$format]['headers']);
             if (!empty($headers)) {
                 foreach ($headers as $headerName => $headerValue) {
                     switch (strtolower($headerName)) {
                         case 'x-priority':
                             $this->_mailer->setPriority((int) $headerValue);
                             break;
                         default:
                             $this->_mailer->getHeaders()->addTextHeader($headerName, $headerValue);
                             break;
                     }
                 }
             }
         }
         if (!empty($this->_blocks[$format]['body'])) {
             $this->_mailer->setBody($this->_blocks[$format]['body'], $format == 'text' ? 'text/plain' : 'text/html');
         }
         if (!empty($this->_blocks[$format]['from'])) {
             $from = explode("\n", str_replace("\r", '', $this->_blocks[$format]['from']));
             if (count($from)) {
                 foreach ($from as $fromString) {
                     $fromItem = explode('<', $fromString);
                     if (count($fromItem) > 1) {
                         $fromName = trim($fromItem[0]);
                         $fromEmail = trim(str_replace('>', '', $fromItem[1]));
                     } else {
                         $fromName = trim($fromItem[0]);
                         $fromEmail = trim($fromItem[0]);
                     }
                     $this->_mailer->setFrom(array($fromEmail => $fromName));
                     $this->_mailer->setReturnPath($fromEmail);
                 }
             }
         }
         if (!empty($this->_blocks[$format]['transport'])) {
             $transport = explode("\n", str_replace("\r", '', $this->_blocks[$format]['transport']));
             if (!empty($transport)) {
                 $transportParams = array();
                 foreach ($transport as $transportKey => $transportString) {
                     $transportString = trim($transportString);
                     if (!empty($transportString)) {
                         $transportItem = explode(':', $transportString);
                         if (count($transportItem) > 1) {
                             $transportItemKey = trim($transportItem[0]);
                             unset($transportItem[0]);
                             $transportItemValue = trim(implode(':', $transportItem));
                             $transportParams[$transportItemKey] = $transportItemValue;
                         }
                     }
                 }
             }
             if (empty($transportParams['type'])) {
                 throw new rad_exception('Error in mailtemplate "' . $this->getTemplateName() . '" at transport block: type of the transport required!');
             }
             switch (strtolower($transportParams['type'])) {
                 case 'smtp':
                     if (empty($transportParams['host']) or empty($transportParams['port']) or empty($transportParams['user']) or !isset($transportParams['password'])) {
                         throw new rad_exception('Error in mailtemplate "' . $this->getTemplateName() . '" at transport block: Not enouph actual params!');
                     }
                     $this->_transportInstance = Swift_SmtpTransport::newInstance($transportParams['host'], $transportParams['port'])->setUsername($transportParams['user'])->setPassword($transportParams['password']);
                     if (!empty($transportParams['security'])) {
                         $this->_transportInstance->setEncryption($transportParams['security']);
                     }
                     break;
                 case 'mail':
                     $this->_transportInstance = Swift_MailTransport::newInstance();
                     break;
                 default:
                     throw new rad_exception('Error in mailtemplate "' . $this->getTemplateName() . '" Unknown transport type "' . $transportParams['type'] . '"!');
                     break;
             }
             //switch
         }
         $this->_mailer->setTo($to);
         $this->_mailer->setCharset('utf-8');
         if (!$this->_transportInstance) {
             $this->_transportInstance = Swift_MailTransport::newInstance();
         }
         return rad_mailtemplate::getMailer($this->_transportInstance)->send($this->_mailer);
     } else {
         $headers = 'MIME-Version: 1.0' . PHP_EOL;
         $headers .= 'Content-Transfer-Encoding: base64' . PHP_EOL;
         $headers .= 'From: ' . $this->_blocks[$format]['from'] . PHP_EOL;
         switch ($format) {
             case 'text':
                 $headers = 'Content-Type: text/plain; charset=utf-8' . PHP_EOL;
                 break;
             case 'html':
                 $headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
                 break;
             default:
                 throw new rad_exception('Unknown format: "' . $format . '"');
                 break;
         }
         if (!empty($this->_blocks[$format]['Cc'])) {
             $headers .= 'Cc: ' . $this->_blocks[$format]['Cc'] . PHP_EOL;
         }
         if (!empty($this->_blocks[$format]['Bcc'])) {
             $headers .= 'Bcc: ' . $this->_blocks[$format]['Bcc'] . PHP_EOL;
         }
         if (!empty($this->_blocks[$format]['headers'])) {
             $headers .= $this->_blocks[$format]['headers'];
         }
         if (is_array($to)) {
             $toString = '';
             foreach ($to as $toEmail => $toName) {
                 $toString .= $toName . ' <' . $toEmail . '>,';
             }
             $to = substr($toString, 0, strlen($toString) - 1);
         }
         return mail($to, $this->_blocks[$format]['subject'], chunk_split(base64_encode($this->_blocks[$format]['body'])), $headers);
     }
 }
 /**
  * Sends messages using the given transport instance.
  *
  * @param \Swift_Transport $transport A transport instance
  * @param string[]         &$failedRecipients An array of failures by-reference
  *
  * @return int The number of sent emails
  */
 public function flushQueue(\Swift_Transport $transport, &$failedRecipients = null)
 {
     $repoClass = $this->doc->getManager()->getRepository($this->entityClass);
     $limit = $this->getMessageLimit();
     $limit = $limit > 0 ? $limit : null;
     $emails = $repoClass->findBy(array("status" => EmailInterface::STATUS_READY, "environment" => $this->environment), null, $limit);
     if (!count($emails)) {
         return 0;
     }
     $failedRecipients = (array) $failedRecipients;
     $count = 0;
     $time = time();
     foreach ($emails as $email) {
         $email->setStatus(EmailInterface::STATUS_PROCESSING);
         $this->doc->getManager()->persist($email);
         $this->doc->getManager()->flush($email);
         $message = unserialize($email->getMessage());
         if (!$transport->isStarted()) {
             $transport->start();
         }
         $count += $transport->send($message, $failedRecipients);
         $transport->stop();
         if ($this->keepSentMessages === true) {
             $email->setStatus(EmailInterface::STATUS_COMPLETE);
             $this->doc->getManager()->persist($email);
         } else {
             $this->doc->getManager()->remove($email);
         }
         $this->doc->getManager()->flush($email);
         if ($this->getTimeLimit() && time() - $time >= $this->getTimeLimit()) {
             break;
         }
     }
     return $count;
 }
 /**
  * Sends messages using the given transport instance.
  *
  * @param Swift_Transport $transport        A transport instance
  * @param string[]        $failedRecipients An array of failures by-reference
  *
  * @return int The number of sent e-mails
  */
 public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
 {
     if (!$transport->isStarted()) {
         $transport->start();
     }
     $limit = $this->getMessageLimit();
     $limit = $limit > 0 ? $limit : null;
     $failedRecipients = (array) $failedRecipients;
     $count = 0;
     $time = time();
     $timeLimit = $this->getTimeLimit();
     try {
         $results = $this->pdo->query('SELECT ' . $this->pkey . ' as pkey, ' . $this->messageField . ' as email FROM ' . $this->table . ' WHERE ' . $this->timeField . ' IS NULL');
         $ustmt = $this->pdo->prepare('UPDATE ' . $this->table . ' SET ' . $this->timeField . ' = ? WHERE ' . $this->pkey . ' = ?');
         $dstmt = $this->pdo->prepare('DELETE FROM ' . $this->table . ' WHERE ' . $this->pkey . ' = ?');
         foreach ($results->fetchAll(PDO::FETCH_COLUMN) as $result) {
             $id = $result[0];
             $ustmt->execute(array(time(), $result[0]));
             $message = unserialize($result[1]);
             $count += $transport->send($message, $failedRecipients);
             $dstmt->execute(array($id));
             if ($limit && $count >= $limit) {
                 break;
             }
             if ($timeLimit && time() - $time >= $timeLimit) {
                 break;
             }
         }
         return $count;
     } catch (\Exception $e) {
         throw new Swift_IoException("Could not access database", 0, $e);
     }
 }
  /**
   * Sends messages using the given transport instance.
   *
   * @param Swift_Transport $transport         A transport instance
   * @param string[]        &$failedRecipients An array of failures by-reference
   *
   * @return int The number of sent emails
   */
  public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
  {
    $table = Doctrine_Core::getTable($this->model);
    //$objects = $table->{$this->method}()->limit($this->getMessageLimit())->execute();
    $objects = $table->lockAndFetch( $this->getMessageLimit(), $this->getTimeLimit() )->execute();
    
    // print_r( $objects, false);
        
    $count = 0;
    
    if ( $objects->count() > 0 )
    {
      
      if (!$transport->isStarted())
      {
        $transport->start();
      }
        
      $time = time();
      
      // TODO
      // loop while ( $mail = MailQueue::getNext() )
      // --> Lock / Checkout 1 Mail
      // 1. check STATUS
      // 2. set STATUS to "SENDING"
      
      foreach ($objects as $object)
      {
        //$message = unserialize($object->{$this->column});
        $message = $object->getMessage(); // is unserialized
        


        // $message->setTo('topo@localhost');
        // $message->setCc('');
        // $message->setBcc('');
        
        try
        {

        //
        // TODO
        //
        // add queue id to metadata
        //
        // $message->getHeaders()->addTextHeader('X-MC-Metadata', json_encode( array( 'spool_id' => $object->id )));
        //

          $count += $transport->send($message, $failedRecipients);
          
          // TODO
          // set STATUS to sent
          $object->setSent();
          
          // $object->setSent();
          
        }
        catch (Exception $e)
        {
          // TODO
          // 1. UNLOCK Mail for another try
          // 2. mark as failed
          
          echo $e;
          break;
        }
        
        if ($this->getTimeLimit() && (time() - $time) >= $this->getTimeLimit())
        {
          break;
        }
      }
    }
    
    return $count;
  }