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(); } }
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; }
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; }
/** * 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; }
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'); }
/** * 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 swiftIt($subject, $msg) { if (empty($subject) || empty($msg)) { return false; } $email = $this->toEmail; $ret = false; if (self::emailIsValid($this->toEmail)) { $name = $this->toName; $from = $this->fromEmail; $fromName = $this->fromName; try { //Start Swift $swift = new Swift(new Swift_Connection_SMTP(defined('SMTP_SERVER') ? SMTP_SERVER : '127.0.0.1:25')); //Create the message $message = new Swift_Message($subject, $msg); //customize names $to = new Swift_Address($email, $name); $from = new Swift_Address($from, $fromName); //Now check if Swift actually sends it if ($swift->send($message, $to, $from)) { $log = "sent mail to: {$to}\n"; $ret = true; } } catch (Swift_ConnectionException $e) { $log = "There was a problem communicating with SMTP: " . $e->getMessage() . "\n"; } catch (Swift_Message_MimeException $e) { $log = "There was an unexpected problem building the email:" . $e->getMessage() . "\n"; } } return $ret; }
/** * 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; } }
/** * 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; } }
/** * 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("*****@*****.**")); } }
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(); } } }
/** * 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("*****@*****.**")); } }
/** * 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; } }
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; } }
/** * Run a batch send in a fail-safe manner. * This operates as Swift::batchSend() except it deals with errors itself. * @param Swift_Message To send * @param Swift_RecipientList Recipients (To: only) * @param Swift_Address The sender's address * @return int The number sent to */ function send(&$message, &$recipients, $sender, $modified_subject = array()) { $sent = 0; $successive_fails = 0; set_error_handler(array(&$this, "handleError")); foreach ($recipients->getTo() as $recipient) { $loop = true; $tries = 0; while ($loop && $tries < $this->getMaxTries()) { $tries++; $loop = false; $this->copyMessageHeaders($message); //BOF:mod if (!empty($modified_subject)) { $temp = $modified_subject[$recipient->getAddress()]; if (!empty($temp)) { $message->setSubject($temp); } } //EOF:mod $sent += $n = $this->swift->send($message, $recipient, $sender, $modified_subject); if (!$n) { $this->addFailedRecipient($recipient->getAddress()); } if ($this->doRestart) { $successive_fails++; $this->restoreMessageHeaders($message); if (($max = $this->getMaxSuccessiveFailures()) && $successive_fails > $max) { restore_error_handler(); Swift_Errors::trigger(new Swift_Exception("Too many successive failures. BatchMailer is configured to allow no more than " . $max . " successive failures.")); return; } $loop = true; //Give it one more shot if ($t = $this->getSleepTime()) { sleep($t); } $this->forceRestartSwift(); } else { $successive_fails = 0; } } } restore_error_handler(); return $sent; }
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; } } }
public function executeFeedback(sfWebRequest $request) { $this->forward404(); $this->forward404Unless($this->getUser()->isAuthenticated()); $this->forward404Unless(sfConfig::get('app_feedback_active', false)); if ($request->isMethod('post')) { $mailer = new Swift($this->getGmailConnection(sfConfig::get('app_feedback_sender_email', '*****@*****.**'), sfConfig::get('app_feedback_sender_password', 'swordfish'))); $name = sprintf('%s (%s)', $this->getUser()->getGuardUser()->getFullname(), $this->getUser()->getUsername()); $message = new Swift_Message(); $message->setFrom($name); $message->setSubject('Feedback leergemeenschap ' . $name); $message->setBody("Feedback van {$name} met als email {$this->getUser()->getEmail()}:\n\n{$request->getParameter('body')}"); $recipients = new Swift_RecipientList(); foreach (sfConfig::get('app_feedback_feedback_email', array('*****@*****.**')) as $recipient) { $recipients->addTo($recipient); } $mailer->send($message, $recipients, $this->getUser()->getEmail()); $this->getUser()->setFlash('notice', 'Je bericht is verstuurd!'); } }
public function executeNew(sfWebRequest $request) { // Display the form $this->form = new ContestForm(); if ($this->getRequest()->isMethod('post')) { $this->form->bind($request->getParameter('contest')); if ($this->form->isValid()) { $contest = new contest(); $contest->setEmail($this->form->getValue('email')); $contest->setUrl($this->form->getValue('url')); $contest->setAdmin_hash(md5(time() . $this->form->getValue('url') . $this->form->getValue('email'))); $contest->setPublic_hash(md5(time() . $this->form->getValue('email') . $this->form->getValue('url'))); $contest->save(); // Send mail with secret URL 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' => $contest->getAdmin_hash(), 'contest_url' => $contest->getUrl()); $v = $this->getPartial('newcontestMailHtmlBody', $mailContext); $htmlPart = new Swift_Message_Part($v, 'text/html'); $message->attach($htmlPart); $message->attach(new Swift_Message_Part($this->getPartial('newcontestMailTextBody', $mailContext), 'text/plain')); $mailTo = $contest->getEmail(); $mailFrom = sfConfig::get('app_mail_webmaster'); $mailer->send($message, $mailTo, $mailFrom); $mailer->disconnect(); } catch (Exception $e) { $this->logMessage($e); } //redirect to the thank you page $this->redirect('contest/thankyou'); } } else { return sfView::SUCCESS; } }
public function executeSignUp($request) { $this->form = new SignUpForm(); if ($request->isMethod('get')) { return; } $this->form->bind($request->getParameter('form')); if (!$this->form->isValid()) { return; } $sfGuardUser = new sfGuardUser(); $sfGuardUser->setUsername($this->form->getValue('username')); $sfGuardUser->setPassword($this->form->getValue('password')); $sfGuardUser->setIsActive(false); $sfGuardUser->save(); $sfGuardUserProfile = new sfGuardUserProfile(); $sfGuardUserProfile->setSfGuardUser($sfGuardUser); $sfGuardUserProfile->setEmail($this->form->getValue('email')); $sfGuardUserProfile->setFirstName($this->form->getValue('first_name')); $sfGuardUserProfile->setLastName($this->form->getValue('last_name')); $sfGuardUserProfile->setGender($this->form->getValue('gender')); $sfGuardUserProfile->setBirthday($this->form->getValue('birthday')); $sfGuardUserProfile->setWebpage($this->form->getValue('webpage')); $sfGuardUserProfile->save(); try { $connection = new Swift_Connection_SMTP('mail.sis-nav.com', 25); $connection->setUsername('*****@*****.**'); $connection->setPassword('gahve123'); $mailer = new Swift($connection); $message = new Swift_Message('Account Confirmation'); $mailContext = array('email' => $sfGuardUserProfile->getEmail(), 'full_name' => $sfGuardUserProfile->getFullName(), 'activation_key' => $sfGuardUserProfile->getActivationKey()); $message->attach(new Swift_Message_Part($this->getPartial('mail/signUpHtmlBody', $mailContext), 'text/html')); $message->attach(new Swift_Message_Part($this->getPartial('mail/signUpTextBody', $mailContext), 'text/plain')); $mailer->send($message, $sfGuardUserProfile->getEmail(), '*****@*****.**'); $mailer->disconnect(); } catch (Exception $e) { $mailer->disconnect(); } $this->getUser()->setFlash('info', 'A confirmation email has been sent to your email address.'); $this->forward('site', 'message'); }
/** * Example of sending a multipart email using SMTP * */ public function executeThankYou() { // Create our connection, in this case an SMTP connection $conn = new Swift_Connection_SMTP(sfConfig::get('mod_sfswiftmailer_smtp_host')); // Need auth for SMTP $conn->setUsername(sfConfig::get('mod_sfswiftmailer_smtp_user')); $conn->setPassword(sfConfig::get('mod_sfswiftmailer_smtp_pass')); $mailer = new Swift($conn); // Get our message bodies $htmlBody = $this->getPresentationFor('sfSwiftMailer', 'thankYouHtml'); $textBody = $this->getPresentationFor('sfSwiftMailer', 'thankYouText'); //Create a message $message = new Swift_Message("The Subject"); //Add some "parts" $message->attach(new Swift_Message_Part($textBody)); $message->attach(new Swift_Message_Part($htmlBody, "text/html")); // Send out our mailer $mailer->send($message, '*****@*****.**', '*****@*****.**'); $mailer->disconnect(); return sfView::SUCCESS; }
public function executeApproveUser($request) { if ($request->isMethod('post')) { if (!($apiUser = Doctrine::getTable('ApiUser')->find($request->getParameter('id')))) { $this->forward404(); } $apiUser->is_active = 1; $apiUser->save(); //send approval email $mailBody = $this->getPartial('accountcreatenotify', array('user' => $apiUser)); $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_api_sender_address'), sfConfig::get('app_api_sender_name')); $recipients = new Swift_RecipientList(); $recipients->addTo($apiUser['email'], $apiUser['name_first'] . ' ' . $apiUser['name_last']); $recipients->addBcc(sfConfig::get('app_api_sender_address')); $mailer->send($message, $recipients, $from); $mailer->disconnect(); } $this->redirect('api/users'); }
/** * Envía un email a través de la configuración de campanias de la empresa que se pasa como parámetro. Utiliza el plugin sfSwiftPlugin * @param id_empresa, identificador de la empresa a través de la que se envia el mensaje. * @param asunto, asunto del mensaje * @param cuerpo, cuerpo del mensaje * @param lista_emails, lista de emails, a los que se envia el mensjae. * @return integer, número de mensajes enviados * @version 25-02-09 * @author Ana Martin */ public static function enviarEmailDefault($id_empresa, $asunto, $cuerpo, $lista_emails) { $empresa = EmpresaPeer::retrievebypk($id_empresa); if ($empresa instanceof Empresa) { $smtp_server = $empresa->getSmtpServer(); $smtp_user = $empresa->getSmtpUser(); $smtp_password = $empresa->getSmtpPassword(); $smtp_port = $empresa->getSmtpPort(); $sender_email = $empresa->getSenderAddress(); $sender_name = $empresa->getSenderName(); //$c = new Criteria(); //$c->add(PlantillaPeer::ID_EMPRESA, $empresa->getIdEmpresa()); //$plantilla = PlantillaPeer::doSelectOne($c); $plantilla = ""; $cuerpo = MensajePeer::prepararMailingCuerpoDefault($cuerpo, $plantilla, $asunto); $smtp = new Swift_Connection_SMTP($smtp_server, $smtp_port); $smtp->setUsername($smtp_user); $smtp->setpassword($smtp_password); $mailer = new Swift($smtp); $message = new Swift_Message(utf8_decode($asunto)); $message->attach(new Swift_Message_Part($cuerpo, "text/html")); $recipients = new Swift_RecipientList(); foreach ($lista_emails as $email) { $recipients->addTo($email); } //Load the plugin with these replacements /* $replacaments = array( '{FECHA}' => date('d-m-Y') , '{ASUNTO}' => utf8_decode($asunto), '{MENSAJE}' => utf8_decode($cuerpo), ); $mailer->attachPlugin(new Swift_Plugin_Decorator($replacaments), "decorator");*/ $enviado_por = new Swift_Address($sender_email, $sender_name); $cuantos = $mailer->send($message, $recipients, $enviado_por); $mailer->disconnect(); return $cuantos; } else { return 0; } }
public function execute($filterChain) { $request = $this->getContext()->getRequest(); $sessionUser = $this->getContext()->getUser(); if ($sessionUser->isAuthenticated() && !$sessionUser->hasCredential('admin') && !$sessionUser->hasCredential('deleter') && $request->isMethod('post') && $request->getParameter('action') != 'descriptions') { $user = $sessionUser->getGuardUser(); $params = array_diff_key($request->getParameterHolder()->getAll(), array('module' => null, 'action' => null)); //log form post $post = new UserFormPost(); $post->User = $user; $post->module = $request->getParameter('module'); $post->action = $request->getParameter('action'); $post->params = in_array($request->getParameter('action'), array('signin', 'join', 'changePassword')) ? null : http_build_query($params); $post->save(); //check for badness $banned = false; $fiveMinutesAgo = date('Y-m-d H:i:s', time() - 5 * 60); $q = LsDoctrineQuery::create()->from('UserFormPost p')->where('p.user_id = ? AND p.created_at > ?', array($user->id, $fiveMinutesAgo))->orderBy('p.created_at DESC'); if ($q->count() > 40) { //BAD! logout and de-activate user $sessionUser->setAuthenticated(false); $user->is_active = false; $user->save(); $banned = true; } if ($q->count() > 20) { //SUSPICIOUS! notify admins sfLoader::loadHelpers('Partial'); $mailBody = get_partial('home/formpostnotify', array('user' => $user, 'posts' => $q->execute(), 'banned' => $banned)); $mailer = new Swift(new Swift_Connection_NativeMail()); $message = new Swift_Message('Suspicious user activity', $mailBody, 'text/plain'); $address = new Swift_Address(sfConfig::get('app_mail_alert_sender_address'), sfConfig::get('app_mail_alert_sender_name')); $mailer->send($message, sfConfig::get('app_mail_alert_recipient_address'), $address); $mailer->disconnect(); $this->sent = true; } } $filterChain->execute(); }
/** * Run a batch send in a fail-safe manner. * This operates as Swift::batchSend() except it deals with errors itself. * @param Swift_Message To send * @param Swift_RecipientList Recipients (To: only) * @param Swift_Address The sender's address * @return int The number sent to */ public function send(Swift_Message $message, Swift_RecipientList $recipients, $sender) { $sent = 0; $successive_fails = 0; $it = $recipients->getIterator("to"); while ($it->hasNext()) { $it->next(); $recipient = $it->getValue(); $tried = 0; $loop = true; while ($loop && $tried < $this->getMaxTries()) { try { $tried++; $loop = false; $this->copyMessageHeaders($message); $sent += $n = $this->swift->send($message, $recipient, $sender); if (!$n) { $this->addFailedRecipient($recipient->getAddress()); } $successive_fails = 0; } catch (Exception $e) { $successive_fails++; $this->restoreMessageHeaders($message); if (($max = $this->getMaxSuccessiveFailures()) && $successive_fails > $max) { throw new Exception("Too many successive failures. BatchMailer is configured to allow no more than " . $max . " successive failures."); } //If an exception was thrown, give it one more go if ($t = $this->getSleepTime()) { sleep($t); } $this->forceRestartSwift(); $loop = true; } } } return $sent; }
protected function execute($arguments = array(), $options = array()) { $configuration = ProjectConfiguration::getApplicationConfiguration($arguments['application'], $options['env'], true); $databaseManager = new sfDatabaseManager($configuration); $databaseManager->initialize($configuration); $db = Doctrine_Manager::connection(); //get scheduled emails $q = LsDoctrineQuery::create()->from('ScheduledEmail se')->where('se.is_sent = ?', false)->limit($options['limit'])->orderBy('se.id'); foreach ($q->execute() as $email) { $mailer = new Swift(new Swift_Connection_NativeMail()); if ($email->body_html) { $message = new Swift_Message($email->subject); $message->attach(new Swift_Message_Part($email->body_text)); $message->attach(new Swift_Message_Part($email->body_html, 'text/html')); } else { $message = new Swift_Message($email->subject, $email->body_text, 'text/plain'); } $from_address = new Swift_Address($email->from_email, $email->from_name); $to_address = new Swift_Address($email->to_email, $email->to_name); if ($sent = $mailer->send($message, $to_address, $from_address)) { $email->is_sent = true; $email->save(); echo "Successfully sent scheduled email #" . $email->id . "\n"; echo " From: " . $email->from_email . "\n"; echo " To: " . $email->to_email . "\n"; echo " Subject: " . $email->subject . "\n"; echo "\n"; } else { echo "Error sending scheduled email #" . $email->id . "\n"; echo "\n"; } $mailer->disconnect(); } //DONE LsCli::beep(); }
public static function Send($id_lang, $template, $subject, $templateVars, $to, $toName = NULL, $from = NULL, $fromName = NULL, $fileAttachment = NULL, $modeSMTP = NULL, $templatePath = _PS_MAIL_DIR_) { $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME', 'PS_MAIL_SMTP_ENCRYPTION', 'PS_MAIL_SMTP_PORT', 'PS_MAIL_METHOD', 'PS_MAIL_TYPE')); if (!isset($configuration['PS_MAIL_SMTP_ENCRYPTION'])) { $configuration['PS_MAIL_SMTP_ENCRYPTION'] = "off"; } if (!isset($configuration['PS_MAIL_SMTP_PORT'])) { $configuration['PS_MAIL_SMTP_PORT'] = "default"; } if (!isset($from)) { $from = $configuration['PS_SHOP_EMAIL']; } if (!isset($fromName)) { $fromName = $configuration['PS_SHOP_NAME']; } if (!empty($from) and !Validate::isEmail($from) or !empty($fromName) and !Validate::isMailName($fromName) or !is_array($to) and !Validate::isEmail($to) or !empty($toName) and !Validate::isMailName($toName) or !is_array($templateVars) or !Validate::isTplName($template) or !Validate::isMailSubject($subject)) { die(Tools::displayError('Error: mail parameters are corrupted')); } /* Construct multiple recipients list if needed */ if (is_array($to)) { $to_list = new Swift_RecipientList(); foreach ($to as $key => $addr) { $to_name = NULL; $addr = trim($addr); if (!Validate::isEmail($addr)) { die(Tools::displayError('Error: mail parameters are corrupted')); } if ($toName and is_array($toName) and Validate::isGenericName($toName[$key])) { $to_name = $toName[$key]; } $to_list->addTo($addr, $to_name); } $to_plugin = $to[0]; $to = $to_list; } else { /* Simple recipient, one address */ $to_plugin = $to; $to = new Swift_Address($to, $toName); } try { /* Connect with the appropriate configuration */ if (intval($configuration['PS_MAIL_METHOD']) == 2) { $connection = new Swift_Connection_SMTP($configuration['PS_MAIL_SERVER'], $configuration['PS_MAIL_SMTP_PORT'], $configuration['PS_MAIL_SMTP_ENCRYPTION'] == "ssl" ? Swift_Connection_SMTP::ENC_SSL : ($configuration['PS_MAIL_SMTP_ENCRYPTION'] == "tls" ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF)); $connection->setTimeout(4); if (!$connection) { return false; } if (!empty($configuration['PS_MAIL_USER']) and !empty($configuration['PS_MAIL_PASSWD'])) { $connection->setUsername($configuration['PS_MAIL_USER']); $connection->setPassword($configuration['PS_MAIL_PASSWD']); } } else { $connection = new Swift_Connection_NativeMail(); } if (!$connection) { return false; } $swift = new Swift($connection); /* Get templates content */ $iso = Language::getIsoById(intval($id_lang)); if (!$iso) { die(Tools::displayError('Error - No iso code for email !')); } $template = $iso . '/' . $template; if (!file_exists($templatePath . $template . '.txt') or !file_exists($templatePath . $template . '.html')) { die(Tools::displayError('Error - The following email template is missing:') . ' ' . $templatePath . $template . '.txt'); } $templateHtml = file_get_contents($templatePath . $template . '.html'); $templateTxt = strip_tags(html_entity_decode(file_get_contents($templatePath . $template . '.txt'), NULL, 'utf-8')); include_once dirname(__FILE__) . '/../mails/' . $iso . '/lang.php'; global $_LANGMAIL; /* Create mail and attach differents parts */ $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME') . '] ' . ((is_array($_LANGMAIL) and key_exists($subject, $_LANGMAIL)) ? $_LANGMAIL[$subject] : $subject)); $templateVars['{shop_logo}'] = file_exists(_PS_IMG_DIR_ . 'logo.jpg') ? $message->attach(new Swift_Message_Image(new Swift_File(_PS_IMG_DIR_ . 'logo.jpg'))) : ''; $templateVars['{shop_name}'] = htmlentities(Configuration::get('PS_SHOP_NAME'), NULL, 'utf-8'); $templateVars['{shop_url}'] = 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . __PS_BASE_URI__; $swift->attachPlugin(new Swift_Plugin_Decorator(array($to_plugin => $templateVars)), 'decorator'); if ($configuration['PS_MAIL_TYPE'] == 3 or $configuration['PS_MAIL_TYPE'] == 2) { $message->attach(new Swift_Message_Part($templateTxt, 'text/plain', '8bit', 'utf-8')); } if ($configuration['PS_MAIL_TYPE'] == 3 or $configuration['PS_MAIL_TYPE'] == 1) { $message->attach(new Swift_Message_Part($templateHtml, 'text/html', '8bit', 'utf-8')); } if ($fileAttachment and isset($fileAttachment['content']) and isset($fileAttachment['name']) and isset($fileAttachment['mime'])) { $message->attach(new Swift_Message_Attachment($fileAttachment['content'], $fileAttachment['name'], $fileAttachment['mime'])); } /* Send mail */ $send = $swift->send($message, $to, new Swift_Address($from, $fromName)); $swift->disconnect(); return $send; } catch (Swift_ConnectionException $e) { return false; } }
public static function sendMailTest($smtpChecked, $smtpServer, $content, $subject, $type, $to, $from, $smtpLogin, $smtpPassword, $smtpPort = 25, $smtpEncryption) { $swift = null; $result = false; 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, Configuration::get('PS_MAIL_DOMAIN')); } else { $swift = new Swift(new Swift_Connection_NativeMail(), Configuration::get('PS_MAIL_DOMAIN')); } $message = new Swift_Message($subject, $content, $type); if ($swift->send($message, $to, $from)) { $result = true; } $swift->disconnect(); } catch (Swift_ConnectionException $e) { $result = $e->getMessage(); } catch (Swift_Message_MimeException $e) { $result = $e->getMessage(); } return $result; }