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 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; } }
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 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; }
/** * 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; } }
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(); } }
/** * Try to authenticate using the username and password * Returns false on failure * @param string The username * @param string The password * @param Swift The instance of Swift this authenticator is used in * @return boolean */ public function isAuthenticated($user, $pass, Swift $swift) { $log = Swift_LogContainer::getLog(); if ($log->hasLevel(Swift_Log::LOG_EVERYTHING)) { $log->add("Trying POP3 Before SMTP authentication. Disconnecting from SMTP first."); } $swift->disconnect(); try { $this->connection->start(); $this->connection->assertOk($this->connection->read()); $this->connection->write("USER " . $user); $this->connection->assertOk($this->connection->read()); $this->connection->write("PASS " . $pass); $this->connection->assertOk($this->connection->read()); $this->connection->write("QUIT"); $this->connection->assertOk($this->connection->read()); $this->connection->stop(); } catch (Swift_ConnectionException $e) { if ($log->hasLevel(Swift_Log::LOG_ERRORS)) { $log->add($e->getMessage(),Swift_Log::ERROR); $log->add("POP3 authentication failed."); } return false; } $options = $swift->getOptions(); $swift->setOptions($options | Swift::NO_POST_CONNECT); $swift->connect(); $swift->setOptions($options); return true; }
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; } }
/** * Disconnect mailer * * @param void * @return boolean */ function disconnect() { if ($this->connected && instance_of($this->swift, 'Swift')) { $this->swift->disconnect(); } // if $this->connected = false; }
/** * Restarts Swift forcibly. */ protected function forceRestartSwift() { //Pre-empting problems trying to issue "QUIT" to a dead connection $this->swift->connection->stop(); $this->swift->connection->start(); $this->swift->disconnect(); //Restart swift $this->swift->connect(); }
/** * 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; } } }
/** * Restarts Swift forcibly. */ function forceRestartSwift() { Swift_Errors::reset(); //Pre-empting problems trying to issue "QUIT" to a dead connection $this->swift->connection->stop(); $this->swift->connection->start(); $this->swift->disconnect(); //Restart swift $this->swift->connect(); $this->doRestart = false; }
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'); }
/** * Close the connection to the MTA * @return boolean */ public function close() { if ($this->isConnected()) { try { $this->swift->disconnect(); return true; } catch (Swift_ConnectionException $e) { $this->setError("Disconnect failed:<br />" . $e->getMessage()); } } return false; }
/** * Close the connection to the MTA * @return boolean */ function close() { if ($this->isConnected()) { Swift_Errors::expect($e, "Swift_ConnectionException"); $this->swift->disconnect(); if ($e) { $this->setError("Disconnect failed:<br />" . $e->getMessage()); return false; } Swift_Errors::clear("Swift_ConnectionException"); } return true; }
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 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(); } } }
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; } }
/** * 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(); }
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 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; }
/** * Used for sending errors/notices/warnings to a list of prescribed destinations * @param $subject * @param $msg * @return unknown_type */ public static function sendEmailNotice($subject, $msg) { // register email notification parameters include sfContext::getInstance()->getConfigCache()->checkConfig('config/skuleGlobal.yml'); $connection = new Swift_Connection_SMTP($mailNotificationParams['sender_smtp'], 465, $mailNotificationParams['sender_ssl'] ? Swift_Connection_SMTP::ENC_SSL : Swift_Connection_SMTP::ENC_OFF); $connection->setUsername($mailNotificationParams['sender_username']); $connection->setPassword($mailNotificationParams['sender_password']); $mailer = new Swift($connection); $message = new Swift_Message($subject, $msg); $recipients = new Swift_RecipientList(); foreach ($mailNotificationParams['receiver'] as $address) { $recipients->addTo($address); } $mailer->send($message, $recipients, $mailNotificationParams['sender_address']); $mailer->disconnect(); }
public static function sendMail($subject, $message, $to) { try { $account = Tools::jsonDecode(Configuration::get('MAILJET'), true); $from = $account['EMAIL']; $from_name = Configuration::get('PS_SHOP_NAME'); $mj_mail_server_port = Configuration::get('PS_MAIL_SMTP_PORT'); switch (Configuration::get('PS_MAIL_SMTP_ENCRYPTION')) { case 'tls': $mj_mail_server_encryption = Swift_Connection_SMTP::ENC_TLS; break; case 'ssl': $mj_mail_server_encryption = Swift_Connection_SMTP::ENC_SSL; break; default: $mj_mail_server_encryption = Swift_Connection_SMTP::ENC_OFF; break; } $connection = new Swift_Connection_SMTP(Configuration::get('PS_MAIL_SERVER'), $mj_mail_server_port, $mj_mail_server_encryption); $connection->setUsername($account['API_KEY']); $connection->setPassword($account['SECRET_KEY']); $swift = new Swift($connection); $sMessage = new Swift_Message('[' . $from_name . '] ' . $subject); //$sMessage->headers->setEncoding('Q'); $sMessage->attach(new Swift_Message_Part(strip_tags($message), 'text/plain', '8bit', 'utf-8')); $sMessage->attach(new Swift_Message_Part($message, 'text/html', '8bit', 'utf-8')); /* Send mail */ $send = $swift->send($sMessage, $to, new Swift_Address($from, $from_name)); $swift->disconnect(); return $send; } catch (Swift_Exception $e) { return false; } }
private function sendMail($customer_email, $body, $subject, $id_shop) { $method = (int) Configuration::get('PS_MAIL_METHOD'); if ($method == 3) { return true; } try { if ($method == 2) { $server = Configuration::get('PS_MAIL_SERVER'); $port = Configuration::get('PS_MAIL_SMTP_PORT'); $encryption = Configuration::get('PS_MAIL_SMTP_ENCRYPTION'); $user = Configuration::get('PS_MAIL_USER'); $password = Configuration::get('PS_MAIL_PASSWD'); if (empty($server) || empty($port)) { return 205; } $connection = new Swift_Connection_SMTP($server, $port, $encryption == 'ssl' ? Swift_Connection_SMTP::ENC_SSL : ($encryption == 'tls' ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF)); $connection->setTimeout(4); if (!$connection) { return 206; } if (!empty($user)) { $connection->setUsername($user); } if (!empty($password)) { $connection->setPassword($password); } } else { $connection = new Swift_Connection_NativeMail(); if (!$connection) { return 207; } } $swift = new Swift($connection, Configuration::get('PS_MAIL_DOMAIN', null, null, $id_shop)); $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME', null, null, $id_shop) . '] ' . $subject); $message->setCharset('utf-8'); $message->headers->setEncoding('Q'); if (Context::getContext()->link instanceof Link === false) { Context::getContext()->link = new Link(); } $message->attach(new Swift_Message_Part($body, 'text/html', '8bit', 'utf-8')); /* Send mail */ $swift->send($message, $customer_email, new Swift_Address(Configuration::get('PS_SHOP_EMAIL'), Configuration::get('PS_SHOP_NAME', null, null, $id_shop))); $swift->disconnect(); return true; } catch (Swift_Exception $e) { return 208; } }
public function executeConfirmRegistrationEmail() { // TODO: Remove this? // -> This is all in user/register now $this->user = sfGuardUserPeer::retrieveByPk($this->getRequest()->getAttribute('user_id')); $this->forward404Unless($this->user, 'user not found, cannot send confirmation registration email'); $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('messages', 'confirmRegistrationHtml'); $textBody = $this->getPresentationFor('messages', 'confirmRegistrationText'); //Create a message $message = new Swift_Message("Thank you for joining the Cothink community. Please confirm your email address to complete registration."); //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, $this->user->getUsername(), '*****@*****.**'); $mailer->disconnect(); return sfView::SUCCESS; }
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; } }
/** * Sends notifications *now* * @param mixed $to string or array...the type of address (email, task ID, user ID) is specified below * @param integer $to_type type of $to address * @param integer $type type of notification * @param array $data additional info needed for notification * @access public * @return bool */ function send_now($to, $to_type, $type, $data = array()) { global $db, $fs, $proj; $emails = array(); $jids = array(); $result = true; if (defined('FS_NO_MAIL')) { return true; } switch ($to_type) { case ADDRESS_DONE: // from send_stored() list($emails, $jids) = $to; $data = unserialize($data['message_data']); $subject = $data['subject']; $body = $data['body']; break; case ADDRESS_EMAIL: // this happens on email confirmation, when no user exists $emails = is_array($to) ? $to : array($to); break; case ADDRESS_USER: // list of user IDs list($emails, $jids) = Notifications::user_to_address($to, $type); break; case ADDRESS_TASK: // now we need everyone on the notification list and the assignees list($emails, $jids) = Notifications::task_notifications($to, $type, ADDRESS_EMAIL); $data['task_id'] = $to; break; } if (isset($data['task_id'])) { $data['task'] = Flyspray::getTaskDetails($data['task_id']); // we have project specific options $pid = $db->x->GetOne('SELECT project_id FROM {tasks} WHERE task_id = ?', null, $data['task_id']); $data['project'] = new Project($pid); } if ($to_type != ADDRESS_DONE) { list($subject, $body) = Notifications::generate_message($type, $data); } if (isset($data['task_id'])) { // Now, we add the project contact addresses, // but only if the task is public $data['task'] = Flyspray::getTaskDetails($data['task_id']); if ($data['task']['mark_private'] != '1' && in_array($type, explode(' ', $data['project']->prefs['notify_types']))) { $proj_emails = preg_split('/[\\s,;]+/', $proj->prefs['notify_email'], -1, PREG_SPLIT_NO_EMPTY); $proj_jids = preg_split('/[\\s,;]+/', $proj->prefs['notify_jabber'], -1, PREG_SPLIT_NO_EMPTY); $emails = array_merge($proj_emails, $emails); if ($fs->prefs['global_email']) { $emails[] = $fs->prefs['global_email']; } if ($fs->prefs['global_jabber']) { $jids[] = $fs->prefs['global_jabber']; } $jids = array_merge($proj_jids, $emails); } } // Now we start sending if (count($emails)) { Swift_ClassLoader::load('Swift_Connection_Multi'); Swift_ClassLoader::load('Swift_Connection_SMTP'); $pool = new Swift_Connection_Multi(); // first choose method if ($fs->prefs['smtp_server']) { $split = explode(':', $fs->prefs['smtp_server']); $port = null; if (count($split) == 2) { $fs->prefs['smtp_server'] = $split[0]; $port = $split[1]; } // connection... SSL, TLS or none if ($fs->prefs['email_ssl']) { $smtp = new Swift_Connection_SMTP($fs->prefs['smtp_server'], $port ? $port : SWIFT_SMTP_PORT_SECURE, SWIFT_SMTP_ENC_SSL); } else { if ($fs->prefs['email_tls']) { $smtp = new Swift_Connection_SMTP($fs->prefs['smtp_server'], $port ? $port : SWIFT_SMTP_PORT_SECURE, SWIFT_SMTP_ENC_TLS); } else { $smtp = new Swift_Connection_SMTP($fs->prefs['smtp_server'], $port); } } if ($fs->prefs['smtp_user']) { $smtp->setUsername($fs->prefs['smtp_user']); $smtp->setPassword($fs->prefs['smtp_pass']); } if (defined('FS_SMTP_TIMEOUT')) { $smtp->setTimeout(FS_SMTP_TIMEOUT); } $pool->addConnection($smtp); } else { Swift_ClassLoader::load('Swift_Connection_NativeMail'); // a connection to localhost smtp server as fallback, discarded if there is no such thing available. $pool->addConnection(new Swift_Connection_SMTP()); $pool->addConnection(new Swift_Connection_NativeMail()); } $swift = new Swift($pool); if (isset($data['task_id'])) { $swift->attachPlugin(new NotificationsThread($data['task_id'], $emails, $db), 'MessageThread'); } if (defined('FS_MAIL_DEBUG')) { $swift->log->enable(); Swift_ClassLoader::load('Swift_Plugin_VerboseSending'); $view = new Swift_Plugin_VerboseSending_DefaultView(); $swift->attachPlugin(new Swift_Plugin_VerboseSending($view), "verbose"); } $message = new Swift_Message($subject, $body); // check for reply-to if (isset($data['project']) && $data['project']->prefs['notify_reply']) { $message->setReplyTo($data['project']->prefs['notify_reply']); } if (isset($data['project']) && isset($data['project']->prefs['bounce_address'])) { $message->setReturnPath($data['project']->prefs['bounce_address']); } $message->headers->setCharset('utf-8'); $message->headers->set('Precedence', 'list'); $message->headers->set('X-Mailer', 'Flyspray'); // Add custom headers, possibly if (isset($data['headers'])) { $headers = array_map('trim', explode("\n", $data['headers'])); if ($headers = array_filter($headers)) { foreach ($headers as $header) { list($name, $value) = explode(':', $header); $message->headers->set(sprintf('X-Flyspray-%s', $name), $value); } } } $recipients = new Swift_RecipientList(); $recipients->addTo($emails); // && $result purpose: if this has been set to false before, it should never become true again // to indicate an error $result = $swift->batchSend($message, $recipients, $fs->prefs['admin_email']) === count($emails) && $result; if (isset($data['task_id'])) { $plugin =& $swift->getPlugin('MessageThread'); if (count($plugin->thread_info)) { $stmt = $db->x->autoPrepare('{notification_threads}', array('task_id', 'recipient_id', 'message_id')); $db->x->executeMultiple($stmt, $plugin->thread_info); $stmt->free(); } } $swift->disconnect(); } if (count($jids)) { $jids = array_unique($jids); if (!$fs->prefs['jabber_username'] || !$fs->prefs['jabber_password']) { return $result; } // nothing that can't be guessed correctly ^^ if (!$fs->prefs['jabber_port']) { $fs->prefs['jabber_port'] = 5222; } require_once 'class.jabber2.php'; $jabber = new Jabber($fs->prefs['jabber_username'], $fs->prefs['jabber_password'], $fs->prefs['jabber_security'], $fs->prefs['jabber_port'], $fs->prefs['jabber_server']); $jabber->SetResource('flyspray'); $jabber->login(); foreach ($jids as $jid) { $result = $jabber->send_message($jid, $body, $subject, 'normal') && $result; } } return $result; }