/** * Send scheduled newsletters to all active subscribers. * * @todo Add event listener to swift in order to try resending the newsletter. * * @throws InvalidArgumentException * * @param array $arguments * @param array $options * * @return void */ protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection(); try { $from = sfNewsletterPluginConfiguration::getFromEmail(); } catch (InvalidArgumentException $e) { $this->logSection($this->name, $e->getMessage(), 30, 'ERROR'); throw $e; } $newsletters = NewsletterPeer::retrieveScheduled(new DateTime($options['schedule'])); if (empty($newsletters)) { $this->logSection($this->name, 'There are no newsletters on schedule.'); return; } /* @var $eachNewsletter Newsletter */ foreach ($newsletters as $eachNewsletter) { try { // get recipient list $recipientList = NewsletterRecipientList::createInstanceActiveSubscribers(); $recipientList->addTo($from); // send the mail using swift try { $mailer = new Swift(new Swift_Connection_NativeMail()); $message = new Swift_Message($eachNewsletter->getSubject(), $eachNewsletter->getContent(), $eachNewsletter->getContentType()->getMimeType()); $sent = $mailer->send($message, $recipientList, $from); $mailer->disconnect(); if ($sent < count($recipientList)) { $this->logSection($this->name, sprintf(sfNewsletterPluginConfiguration::EXCEPTION_SWIFT_ERROR . ' Error: Email has not reached all recipients. Successfully sent to %d of %d recipients.', $sent, count($recipientList)), null, 'ERROR'); } } catch (Exception $e) { $mailer->disconnect(); $this->logSection($this->name, sfNewsletterPluginConfiguration::EXCEPTION_SWIFT_ERROR . ' Error: ' . $e->getMessage(), null, 'ERROR'); throw $e; } } catch (RuntimeException $e) { $this->logSection($this->name, $e->getMessage()); throw $e; } } }
<?php require_once dirname(__FILE__) . '/../bootstrap/unit.php'; # load fixtures of this plugin $propelData->loadData(sfConfig::get('sf_plugins_dir') . '/sfNewsletterPlugin/data/fixtures'); $limeTest = new lime_test(4, new lime_output_color()); $recipientList = NewsletterRecipientList::createInstanceActiveSubscribers(); $limeTest->isa_ok($recipientList, 'NewsletterRecipientList', 'NewsletterRecipientList is valid.'); $limeTest->is(count($recipientList), 1, 'Found only valid subscribers.'); $subscriber = new Swift_Address('*****@*****.**', 'fourth subscriber'); /* @var $eachRecipient Swift_Address */ foreach ($recipientList->getBcc() as $eachRecipient) { $limeTest->is($eachRecipient->getName(), $subscriber->getName(), 'Subscriber name ok.'); $limeTest->is($eachRecipient->getAddress(), $subscriber->getAddress(), 'Subscriber email ok.'); }