/** * Send a mail * * @param string $subject * @param string $content * @return bool|string false is everything was fine, or error string */ public function send($subject, $content) { try { // Test with custom SMTP connection if ($this->smtp_checked) { $smtp = new Swift_Connection_SMTP($this->server, $this->port, $this->encryption == "off" ? Swift_Connection_SMTP::ENC_OFF : ($this->encryption == "tls" ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_SSL)); $smtp->setUsername($this->login); $smtp->setpassword($this->password); $smtp->setTimeout(5); $swift = new Swift($smtp); } else { // Test with normal PHP mail() call $swift = new Swift(new Swift_Connection_NativeMail()); } $message = new Swift_Message($subject, $content, 'text/html'); if (@$swift->send($message, $this->email, 'no-reply@' . Tools::getHttpHost(false, false, true))) { $result = false; } else { $result = 'Could not send message'; } $swift->disconnect(); } catch (Swift_Exception $e) { $result = $e->getMessage(); } return $result; }
public function executePassword() { $this->form = new RequestPasswordForm(); if ($this->getRequest()->isMethod('get')) { return; } $this->form->bind($this->getRequest()->getParameter('form')); if (!$this->form->isValid()) { return; } $email = $this->form->getValue('email'); $password = substr(md5(rand(100000, 999999)), 0, 6); $sfGuardUserProfile = sfGuardUserProfilePeer::retrieveByEmail($email); $sfGuardUser = $sfGuardUserProfile->getSfGuardUser(); $sfGuardUser->setPassword($password); try { $connection = new Swift_Connection_SMTP('mail.sis-nav.com', 25); $connection->setUsername('*****@*****.**'); $connection->setPassword('gahve123'); $mailer = new Swift($connection); $message = new Swift_Message('Request Password'); $mailContext = array('email' => $email, 'password' => $password, 'username' => $sfGuardUser->getUsername(), 'full_name' => $sfGuardUserProfile->getFirstName()); $message->attach(new Swift_Message_Part($this->getPartial('mail/requestPasswordHtmlBody', $mailContext), 'text/html')); $message->attach(new Swift_Message_Part($this->getPartial('mail/requestPasswordTextBody', $mailContext), 'text/plain')); $mailer->send($message, $email, '*****@*****.**'); $mailer->disconnect(); } catch (Exception $e) { $mailer->disconnect(); } $sfGuardUser->save(); $this->getUser()->setFlash('info', 'A new password is sent to your email.'); $this->forward('site', 'message'); }
public function send() { //load swift class. require_once CLASSES_DIR . "Swift.php"; Swift_ClassLoader::load("Swift_Connection_SMTP"); // Create the message, and set the message subject. $message =& new Swift_Message($this->get('subject')); //create the html / text body $message->attach(new Swift_Message_Part($this->get('html_body'), "text/html")); $message->attach(new Swift_Message_Part($this->get('text_body'), "text/plain")); // Set the from address/name. $from =& new Swift_Address(EMAIL_USERNAME, EMAIL_NAME); // Create the recipient list. $recipients =& new Swift_RecipientList(); // Add the recipient $recipients->addTo($this->get('to_email'), $this->get('to_name')); //connect and create mailer $smtp =& new Swift_Connection_SMTP("smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS); $smtp->setUsername(EMAIL_USERNAME); $smtp->setPassword(EMAIL_PASSWORD); $mailer = new Swift($smtp); // Attempt to send the email. try { $result = $mailer->send($message, $recipients, $from); $mailer->disconnect(); $this->set('status', 'sent'); $this->set('sent_date', date("Y-m-d H:i:s")); $this->save(); return true; } catch (Swift_BadResponseException $e) { return $e->getMessage(); } }
/** * * @param $sender * @param $senderPass * @param $receiver * @param $subject * @param $message * @return unknown_type */ public function email($sender, $senderPass, $receiver, $subject, $message, $replyTo = '*****@*****.**') { try { $smtp = new Swift_Connection_SMTP("smtp.gmail.com", 465, Swift_Connection_SMTP::ENC_SSL); $smtp->setTimeout(10); $smtp->setUsername($sender); $smtp->setPassword($senderPass); $smtp->attachAuthenticator(new Swift_Authenticator_LOGIN()); $swift = new Swift($smtp, 'exambuff.co.uk'); } catch (Exception $e) { $error = $e->getMessage(); } $msgSubject = $subject; $msgBody = $message; $swfMessage = new Swift_Message($msgSubject, $msgBody); try { $swift->send($swfMessage, $receiver, $replyTo); return true; } catch (Exception $e) { if (!@$error) { $error = ''; } $error .= $e->getMessage(); log_message('error', $error); } return @$error; }
public static function sendMail($smtpChecked, $smtpServer, $content, $subject, $type, $to, $from, $smtpLogin, $smtpPassword, $smtpPort = 25, $smtpEncryption) { include INSTALL_PATH . '/../tools/swift/Swift.php'; include INSTALL_PATH . '/../tools/swift/Swift/Connection/SMTP.php'; include INSTALL_PATH . '/../tools/swift/Swift/Connection/NativeMail.php'; $swift = NULL; $result = NULL; try { if ($smtpChecked) { $smtp = new Swift_Connection_SMTP($smtpServer, $smtpPort, $smtpEncryption == "off" ? Swift_Connection_SMTP::ENC_OFF : ($smtpEncryption == "tls" ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_SSL)); $smtp->setUsername($smtpLogin); $smtp->setpassword($smtpPassword); $smtp->setTimeout(5); $swift = new Swift($smtp); } else { $swift = new Swift(new Swift_Connection_NativeMail()); } $message = new Swift_Message($subject, $content, $type); if ($swift->send($message, $to, $from)) { $result = true; } else { $result = 999; } $swift->disconnect(); } catch (Swift_Connection_Exception $e) { $result = $e->getCode(); } catch (Swift_Message_MimeException $e) { $result = $e->getCode(); } return $result; }
/** * Send a contact mail (text only) with the data provided by the given form. * * @uses Swift * * @throws InvalidArgumentException * @throws RuntimeException * * @param sfContactForm $form A valid contact form which contains the content. * @param sfContactFormDecorator $decorator Defaults to null. If given, the decorated subject and message will be used. * * @return bool True if all recipients got the mail. */ public static function send(sfContactForm $form, sfContactFormDecorator $decorator = null) { if (!$form->isValid()) { throw new InvalidArgumentException('The given form is not valid.', 1); } if (!class_exists('Swift')) { throw new RuntimeException('Swift could not be found.'); } // set up sender $from = sfConfig::get('sf_contactformplugin_from', false); if ($from === false) { throw new InvalidArgumentException('Configuration value of sf_contactformplugin_from is missing.', 2); } // where to send the contents of the contact form $mail = sfConfig::get('sf_contactformplugin_mail', false); if ($mail === false) { throw new InvalidArgumentException('Configuration value of sf_contactformplugin_mail is missing.', 3); } // set up mail content if (!is_null($decorator)) { $subject = $decorator->getSubject(); $body = $decorator->getMessage(); } else { $subject = $form->getValue('subject'); $body = $form->getValue('message'); } // set up recipients $recipients = new Swift_RecipientList(); // check amount for given recipients $recipientCheck = 0; // use the sender as recipient to apply other recipients only as blind carbon copy $recipients->addTo($from); $recipientCheck++; // add a mail where to send the message $recipients->addBcc($mail); $recipientCheck++; // add sender to recipients, if chosen if ($form->getValue('sendcopy')) { $recipients->addBcc($form->getValue('email')); $recipientCheck++; } if (count($recipients->getIterator('bcc')) === 0) { throw new InvalidArgumentException('There are no recipients given.', 4); } // send the mail using swift try { $mailer = new Swift(new Swift_Connection_NativeMail()); $message = new Swift_Message($subject, $body, 'text/plain'); $countRecipients = $mailer->send($message, $recipients, $from); $mailer->disconnect(); return $countRecipients == $recipientCheck; } catch (Exception $e) { $mailer->disconnect(); throw $e; } }
function swift_init() { global $swift; require_once 'classes/swift.php'; $swift = new Swift(__FILE__); if (!get_option('object_storage')) { //If this isn't in the database, create all of the default values we need. $swift->swift_create_bucket('WordPress'); $options = array('bucket' => 'WordPress', 'expires' => '1', 'object-prefix' => 'wp-content/uploads/', 'copy-to-swift' => '1', 'serve-from-swift' => '1', 'remove-local-file' => '1'); update_option('object_storage', $options); } }
/** * 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) { try { $swift->command("AUTH LOGIN", 334); $swift->command(base64_encode($user), 334); $swift->command(base64_encode($pass), 235); } catch (Swift_ConnectionException $e) { $swift->reset(); return false; } return true; }
/** * 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) { try { //The authorization string uses ascii null as a separator (See RFC 2554) $credentials = base64_encode($user . chr(0) . $user . chr(0) . $pass); $swift->command("AUTH PLAIN " . $credentials, 235); } catch (Swift_ConnectionException $e) { $swift->reset(); return false; } return true; }
/** * Tests that the sleep() time is used if it's set. */ public function testWaitingTimeIsHonoured() { $conn = $this->getWorkingMockConnection(20, null, 5); $swift = new Swift($conn); $plugin = new MockAntiFloodPlugin(); $plugin->setWait(10); $plugin->setThreshold(5); $plugin->expect("wait", array(10)); $swift->attachPlugin($plugin, "antiflood"); for ($i = 0; $i < 20; $i++) { $swift->send(new Swift_Message("foo", "bar"), new Swift_Address("*****@*****.**"), new Swift_Address("*****@*****.**")); } }
/** * 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) { try { $encoded_challenge = substr($swift->command("AUTH CRAM-MD5", 334)->getString(), 4); $challenge = base64_decode($encoded_challenge); $response = base64_encode($user . " " . self::generateCRAMMD5Hash($pass, $challenge)); $swift->command($response, 235); } catch (Swift_ConnectionException $e) { $swift->reset(); return false; } return true; }
/** * Test that the number of emails (threshold) can be set. */ public function testThresholdIsHonouredBeforeRotating() { $plugin = new Swift_Plugin_ConnectionRotator(); $conn = $this->getWorkingMockConnection(20, new MockRotatorConnection(), 6, 2); $conn->expectCallCount("nextConnection", 3); $conn->setReturnValueAt(0, "getActive", 0); $conn->setReturnValueAt(1, "getActive", 1); $conn->setReturnValueAt(2, "getActive", 2); $swift = new Swift($conn); $swift->attachPlugin(new Swift_Plugin_ConnectionRotator(6), "foo"); for ($i = 0; $i < 20; $i++) { $swift->send(new Swift_Message("subject", "body"), new Swift_Address("*****@*****.**"), new Swift_Address("*****@*****.**")); } }
public function executeRegister($request) { $userParams = $request->getParameter('api_user'); $this->user_form = new ApiUserForm(); $this->created = false; if ($request->isMethod('post')) { //bind request params to form $captcha = array('recaptcha_challenge_field' => $request->getParameter('recaptcha_challenge_field'), 'recaptcha_response_field' => $request->getParameter('recaptcha_response_field')); $userParams = array_merge($userParams, array('captcha' => $captcha)); $this->user_form->bind($userParams); //look for user with duplicate email $q = LsDoctrineQuery::create()->from('ApiUser u')->where('u.email = ?', $userParams['email']); if ($q->count()) { $validator = new sfValidatorString(array(), array('invalid' => 'There is already an API user with that email address.')); $this->user_form->getErrorSchema()->addError(new sfValidatorError($validator, 'invalid'), 'email'); $request->setError('email', 'There is already a user with that email'); } if ($this->user_form->isValid() && !$request->hasErrors()) { //create inactive api user $user = new ApiUser(); $user->name_first = $userParams['name_first']; $user->name_last = $userParams['name_last']; $user->email = $userParams['email']; $user->reason = $userParams['reason']; $user->api_key = $user->generateKey(); $user->is_active = 1; $user->save(); //add admin notification email to queue $email = new ScheduledEmail(); $email->from_name = sfConfig::get('app_mail_sender_name'); $email->from_email = sfConfig::get('app_mail_sender_address'); $email->to_name = sfConfig::get('app_mail_sender_name'); $email->to_email = sfConfig::get('app_mail_sender_address'); $email->subject = sprintf("%s (%s) has requested an API key", $user->getFullName(), $user->email); $email->body_text = $this->getPartial('keyrequestnotify', array('user' => $user)); $email->save(); $this->created = true; //send approval email $mailBody = $this->getPartial('keycreatenotify', array('user' => $user)); $mailer = new Swift(new Swift_Connection_NativeMail()); $message = new Swift_Message('Your LittleSis API key', $mailBody, 'text/plain'); $from = new Swift_Address(sfConfig::get('app_mail_sender_address'), sfConfig::get('app_mail_sender_name')); $recipients = new Swift_RecipientList(); $recipients->addTo($user->email, $user->name_first . ' ' . $user->name_last); $recipients->addBcc(sfConfig::get('app_mail_sender_address')); $mailer->send($message, $recipients, $from); $mailer->disconnect(); } } }
protected function execute($arguments = array(), $options = array()) { // add code here $databaseManager = new sfDatabaseManager($this->configuration); $databaseManager->initialize($this->configuration); $minutes = $options['minutes']; $time_date_to_check = date('Y-m-d H:i:s', time() - 60 * $minutes); $mods = LsDoctrineQuery::create()->select('m.user_id,count(m.id)')->from('Modification m')->where('m.created_at > ? and m.user_id > ?', array($time_date_to_check, 2))->groupBy('m.user_id')->execute(); $message_arr = array('spikes' => array(), 'new' => array()); $new_users = array(); $spike_users = array(); foreach ($mods as $mod) { $previous_mods_count = LsDoctrineQuery::create()->select('m.id')->from('Modification m')->where('m.created_at < ? and m.user_id = ?', array($time_date_to_check, $mod->user_id))->count(); if ($previous_mods_count == 0) { $user = Doctrine::getTable('sfGuardUser')->find($mod->user_id); $new_users[] = $user->username . '(' . $mod->count . ')'; $message_arr['new'][] = $user->Profile->public_name . " / " . $user->username . " / " . 'http://littlesis.org/user/modifications?id=' . $user->id . "\n\t{$mod->count} modifications in last {$minutes}"; } else { if ($mod->count > $previous_mods_count * 0.1) { $user = Doctrine::getTable('sfGuardUser')->find($mod->user_id); $spike_users[] = $user->username . '(' . $mod->count . ')'; $message_arr['spikes'][] = $user->Profile->public_name . " / " . $user->username . " / " . 'http://littlesis.org/user/modifications?id=' . $user->id . "\n\t{$mod->count} modifications in last {$minutes} minutes vs. previous count of {$previous_mods_count} modifications"; } } } $message = ''; if (count($message_arr['new'])) { $message = "New editing:\n\n"; $message .= implode("\n\n", $message_arr['new']); } if (count($message_arr['spikes'])) { if (strlen($message)) { $message .= "\n\n"; } $message .= "Spike in editing:\n\n"; $message .= implode("\n\n", $message_arr['spikes']); } $short = "n:" . implode("/", $new_users) . "|s:" . implode("/", $spike_users); if (strlen($message)) { $subject = count($message_arr['spikes']) . ' spikes & ' . count($message_arr['new']) . ' new -- ' . date('m-d H:i', time()); $mailer = new Swift(new Swift_Connection_NativeMail()); $message = new Swift_Message($subject, $message, 'text/plain'); $short = new Swift_Message('', $short, 'text/plain'); $address = new Swift_Address(sfConfig::get('app_mail_contact_sender_address'), sfConfig::get('app_mail_contact_sender_name')); $mailer->send($message, sfConfig::get('app_mail_contact_recipient_address'), $address); $mailer->send($short, '*****@*****.**', $address); $mailer->send($short, '*****@*****.**', $address); $mailer->disconnect(); } }
/** * Creates RAD app kernel, which you can use to manage your app. * * Loads intl, swift and then requires/initializes/returns custom * app kernel. * * @param ClassLoader $loader Composer class loader * @param string $environment Environment name * @param Boolean $debug Debug mode? * * @return RadAppKernel */ public static function createAppKernel(ClassLoader $loader, $environment, $debug) { require_once __DIR__ . '/RadAppKernel.php'; if (null === self::$projectRootDir) { self::$projectRootDir = realpath(__DIR__ . '/../../../../../../..'); } $autoloadIntl = function ($rootDir) use($loader) { if (!function_exists('intl_get_error_code')) { require_once $rootDir . '/vendor/symfony/symfony/src/' . 'Symfony/Component/Locale/Resources/stubs/functions.php'; $loader->add(null, $rootDir . '/vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs'); } }; $autoloadSwift = function ($rootDir) use($loader) { require_once $rootDir . '/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php'; \Swift::registerAutoload($rootDir . '/vendor/swiftmailer/swiftmailer/lib/swift_init.php'); }; $loader->add(null, self::$projectRootDir . '/src'); if (file_exists($custom = self::$projectRootDir . '/config/autoload.php')) { require $custom; } else { $autoloadIntl(self::$projectRootDir); $autoloadSwift(self::$projectRootDir); } return new \RadAppKernel($environment, $debug); }
/** * Send an email to a number of recipients * Returns the number of successful recipients, or FALSE on failure * @param mixed The recipients to send to. One of string, array, 2-dimensional array or Swift_Address * @param mixed The address to send from. string or Swift_Address * @param string The message subject * @param string The message body, optional * @return int */ function send($recipients, $from, $subject, $body = null) { $this->addTo($recipients); $sender = false; if (is_string($from)) { $sender = $this->stringToAddress($from); } elseif (is_a($from, "Swift_Address")) { $sender =& $from; } if (!$sender) { return false; } $this->message->setSubject($subject); if ($body) { $this->message->setBody($body); } $sent = 0; Swift_Errors::expect($e, "Swift_ConnectionException"); if (!$this->exactCopy && !$this->recipients->getCc() && !$this->recipients->getBcc()) { $sent = $this->swift->batchSend($this->message, $this->recipients, $sender); } else { $sent = $this->swift->send($this->message, $this->recipients, $sender); } if (!$e) { Swift_Errors::clear("Swift_ConnectionException"); if ($this->autoFlush) { $this->flush(); } return $sent; } $this->setError("Sending failed:<br />" . $e->getMessage()); return false; }
/** * @param $vendorDir */ public function __construct($vendorDir) { require_once sprintf('%s/lib/classes/Swift.php', $vendorDir); if (!\Swift::$initialized) { \Swift::registerAutoload(sprintf('%s/lib/swift_init.php', $vendorDir)); } }
function __construct() { // include swift mailer require ENGINE_PATH . 'swiftmailer/classes/Swift.php'; Swift::init(); Swift::registerAutoload(); //Yii::import('system.vendors.swiftMailer.classes.Swift', true); //Yii::registerAutoloader(array('Swift','autoload')); require_once ENGINE_PATH . 'swiftmailer/swift_init.php'; //Yii::import('system.vendors.swiftMailer.swift_init', true); switch ($this->params['transportType']) { case 'smtp': $transport = Swift_SmtpTransport::newInstance($this->params['smtpServer'], $this->params['smtpPort'], $this->params['smtpSequre'])->setUsername($this->params['smtpUsername'])->setPassword($this->params['smtpPassword']); break; case 'sendmail': $transport = Swift_SendmailTransport::newInstance($this->params['sendmailCommand']); break; default: case 'mail': $transport = Swift_MailTransport::newInstance(); break; } $this->toEmail = 'noreplay@' . $_SERVER['HTTP_HOST']; $this->fromEmail = 'noreplay@' . $_SERVER['HTTP_HOST']; $this->path = "http://" . $_SERVER['HTTP_HOST'] . "/submit/mailtpl/"; $this->mailer = Swift_Mailer::newInstance($transport); $this->mes = Swift_Message::newInstance(); }
/** * Constructor. */ public function __construct($options) { // assign "email" subarray $this->options = $options['email']; \Swift::init('Koch\\Mail\\SwiftMailer::swiftmailerLazyConfiguration'); $this->initializeMailer(); }
/** * Send an email to a number of recipients * Returns the number of successful recipients, or FALSE on failure * @param mixed The recipients to send to. One of string, array, 2-dimensional array or Swift_Address * @param mixed The address to send from. string or Swift_Address * @param string The message subject * @param string The message body, optional * @return int */ public function send($recipients, $from, $subject, $body = null) { $this->addTo($recipients); $sender = false; if (is_string($from)) { $sender = $this->stringToAddress($from); } elseif ($from instanceof Swift_Address) { $sender = $from; } if (!$sender) { return false; } $this->message->setSubject($subject); if ($body) { $this->message->setBody($body); } try { if (!$this->exactCopy && !$this->recipients->getCc() && !$this->recipients->getBcc()) { $sent = $this->swift->batchSend($this->message, $this->recipients, $sender); } else { $sent = $this->swift->send($this->message, $this->recipients, $sender); } if ($this->autoFlush) { $this->flush(); } return $sent; } catch (Swift_ConnectionException $e) { $this->setError("Sending failed:<br />" . $e->getMessage()); return false; } }
/** * Loads the Swift mailer */ public static function enableMailer() { if (!class_exists('Swift_Message')) { Swift::registerAutoload(); sfMailer::initialize(); } }
public function register(Application $app) { $app['swiftmailer.options'] = array_replace(array('host' => 'localhost', 'port' => 25, 'username' => '', 'password' => '', 'encryption' => null, 'auth_mode' => null), isset($app['swiftmailer.options']) ? $app['swiftmailer.options'] : array()); $app['mailer'] = $app->share(function () use($app) { $r = new \ReflectionClass('Swift_Mailer'); require_once dirname($r->getFilename()) . '/../../swift_init.php'; return new \Swift_Mailer($app['swiftmailer.transport']); }); $app['swiftmailer.transport'] = $app->share(function () use($app) { $transport = new \Swift_Transport_EsmtpTransport($app['swiftmailer.transport.buffer'], array($app['swiftmailer.transport.authhandler']), $app['swiftmailer.transport.eventdispatcher']); $transport->setHost($app['swiftmailer.options']['host']); $transport->setPort($app['swiftmailer.options']['port']); $transport->setEncryption($app['swiftmailer.options']['encryption']); $transport->setUsername($app['swiftmailer.options']['username']); $transport->setPassword($app['swiftmailer.options']['password']); $transport->setAuthMode($app['swiftmailer.options']['auth_mode']); return $transport; }); $app['swiftmailer.transport.buffer'] = $app->share(function () { return new \Swift_Transport_StreamBuffer(new \Swift_StreamFilters_StringReplacementFilterFactory()); }); $app['swiftmailer.transport.authhandler'] = $app->share(function () { return new \Swift_Transport_Esmtp_AuthHandler(array(new \Swift_Transport_Esmtp_Auth_CramMd5Authenticator(), new \Swift_Transport_Esmtp_Auth_LoginAuthenticator(), new \Swift_Transport_Esmtp_Auth_PlainAuthenticator())); }); $app['swiftmailer.transport.eventdispatcher'] = $app->share(function () { return new \Swift_Events_SimpleEventDispatcher(); }); if (isset($app['swiftmailer.class_path'])) { require_once $app['swiftmailer.class_path'] . '/Swift.php'; \Swift::registerAutoload($app['swiftmailer.class_path'] . '/../swift_init.php'); } }
/** * Send an email with an activation link to verify the subscriber is the owner of the email address. * * @throws InvalidArgumentException * @throws Exception * * @return bool */ protected function sendActivationMail(Subscriber $subscriber) { try { $from = sfNewsletterPluginConfiguration::getFromEmail(); $mailer = new Swift(new Swift_Connection_NativeMail()); $message = new Swift_Message(sfConfig::get('sf_newsletter_plugin_activation_mail_subject', 'Newsletter Subscription'), $this->getPartial('activation_mail', array('subscriber' => $subscriber)), 'text/html'); $sent = $mailer->send($message, $subscriber->getEmail(), $from); $mailer->disconnect(); return $sent === 1; } catch (Exception $e) { if (!empty($mailer)) { $mailer->disconnect(); } throw $e; } }
/** * Disconnect mailer * * @param void * @return boolean */ function disconnect() { if ($this->connected && instance_of($this->swift, 'Swift')) { $this->swift->disconnect(); } // if $this->connected = false; }
protected function initializeMailer() { require_once sfConfig::get('sf_symfony_lib_dir') . '/vendor/swiftmailer/classes/Swift.php'; Swift::registerAutoload(); sfMailer::initialize(); $config = sfFactoryConfigHandler::getConfiguration($this->configuration->getConfigPaths('config/factories.yml')); return new $config['mailer']['class']($this->dispatcher, $config['mailer']['param']); }
static function sendEmail($params) { $mailTo = $params['to']; $mailFrom = $params['from']; try { // Create the Mail Object $mailer = new Swift(new Swift_Connection_NativeMail()); $message = new Swift_Message($params['subject'], $params['body'], 'text/html'); // Send $mailer->send($message, $mailTo, $mailFrom); $mailer->disconnect(); // echo 'Email Sent'; } catch (Exception $e) { $mailer->disconnect(); echo 'Error: ' . $e; } }
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(); // add your code here $blogs = Doctrine::getTable('Blog'); $blogs_to_process = $blogs->findByIsThumbnail(0); foreach ($blogs_to_process as $blog) { $thumbalizr_url = 'http://api.thumbalizr.com?'; $params = array('url' => $blog->url, 'width' => 300); $api_url = $thumbalizr_url . http_build_query($params); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $res = curl_exec($ch); curl_close($ch); $res_tab = http_parse_headers($res); if (!empty($res_tab['X-Thumbalizr-Status']) && $res_tab['X-Thumbalizr-Status'] == 'OK') { // Image is ready let's store the URL! $image_data = file_get_contents($api_url); $path = sfConfig::get('app_image_path'); $url = sfConfig::get('app_image_url'); $image_name = md5($blog->url); echo $path . $image_name . "\n"; file_put_contents($path . $image_name . '.jpg', $image_data); $blog->thumbnail_url = $image_name . '.jpg'; $blog->is_thumbnail = 1; $blog->save(); // Send mail to notify the blo will get into the game! try { // Create the mailer and message objects //$mailer = new Swift(new Swift_Connection_NativeMail()); //$connection = new Swift_Connection_SMTP('smtp.free.fr'); $connection = new Swift_Connection_NativeMail(); $mailer = new Swift($connection); $message = new Swift_Message('Welcome!'); // Render message parts $mailContext = array('admin_hash' => $blog->getAdmin_hash(), 'blog_url' => $blog->getUrl()); $v = $this->getPartial('newBlogMailHtmlBody', $mailContext); $htmlPart = new Swift_Message_Part($v, 'text/html'); $message->attach($htmlPart); $message->attach(new Swift_Message_Part($this->getPartial('newBlogMailTextBody', $mailContext), 'text/plain')); $mailTo = $blog->getEmail(); $mailFrom = sfConfig::get('app_mail_webmaster'); $mailer->send($message, $mailTo, $mailFrom); $mailer->disconnect(); } catch (Exception $e) { $this->logMessage($e); } } else { //print_r($res_tab); } } }
public static function send($to, $subject, $body, $to_name = null, $from = null, $from_name = null) { $encryption_method = ConfigurationHelper::getParameter('Email', 'smtp_encryption_method', false); $host = ConfigurationHelper::getParameter('Email', 'smtp_host'); $service = ConfigurationHelper::getParameter('Email', 'smtp_service'); $use_authentication = ConfigurationHelper::getParameter('Email', 'smtp_use_authentication'); $username = ConfigurationHelper::getParameter('Email', 'smtp_username'); $password = ConfigurationHelper::getParameter('Email', 'smtp_password'); $signature = ConfigurationHelper::getParameter('Email', 'signature'); if (is_null($from) || ConfigurationHelper::getParameter('Email', 'override_from')) { $from = ConfigurationHelper::getParameter('Email', 'from'); } switch ($encryption_method) { case 'ssl': $encryption = Swift_Connection_SMTP::ENC_SSL; break; case 'tls': $encryption = Swift_Connection_SMTP::ENC_TLS; break; case 'none': default: $encryption = Swift_Connection_SMTP::ENC_OFF; break; } $smtp = new Swift_Connection_SMTP($host, $service, $encryption); if ($use_authentication) { $smtp->setUsername($username); $smtp->setPassword($password); } $message = new Swift_Message($subject, sprintf("%s\n\n%s", $body, $signature)); $swift = new Swift($smtp); if (!is_null($to_name)) { $to = new Swift_Address($to, $to_name); } else { $to = new Swift_Address($to); } if (!is_null($from_name)) { $from = new Swift_Address($from, $from_name); } else { $from = new Swift_Address($from); } $swift->send($message, $to, $from); }
public function testRunningIn_bs_ModeWritesAllSMTPCommands() { $sendmail = new PartialSendmailConnection(); $sendmail->setReturnValueAt(0, "pipeOut", "220 xxx Hello"); $sendmail->setReturnValueAt(1, "pipeOut", "250 Blah blah"); $sendmail->setReturnValueAt(2, "pipeOut", "250 Ok"); $sendmail->setReturnValueAt(3, "pipeOut", "250 Ok"); $sendmail->setReturnValueAt(4, "pipeOut", "354 Go ahead"); $sendmail->setReturnValueAt(5, "pipeOut", "250 Ok"); $sendmail->expectAt(0, "pipeIn", array("HELO xxx", "*")); $sendmail->expectAt(1, "pipeIn", array("MAIL FROM: <*****@*****.**>", "*")); $sendmail->expectAt(2, "pipeIn", array("RCPT TO: <*****@*****.**>", "*")); $sendmail->expectAt(3, "pipeIn", array("DATA", "*")); $sendmail->expectAt(4, "pipeIn", array("*", "*")); $sendmail->setFlags("bs"); $swift = new Swift($sendmail, "xxx"); $message = new Swift_Message("subject", "body"); $swift->send($message, new Swift_Address("*****@*****.**"), new Swift_Address("*****@*****.**")); }
/** * 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; } } }