protected function getConnection() { Swift_LogContainer::getLog()->setLogLevel(Swift_Log::LOG_EVERYTHING); switch (TestConfiguration::CONNECTION_TYPE) { case "smtp": $enc = null; $test_enc = TestConfiguration::SMTP_ENCRYPTION; if ($test_enc == "ssl") { $enc = Swift_Connection_SMTP::ENC_SSL; } elseif ($test_enc == "tls") { $enc = Swift_Connection_SMTP::ENC_TLS; } $conn = new Swift_Connection_SMTP(TestConfiguration::SMTP_HOST, TestConfiguration::SMTP_PORT, $enc); if ($user = TestConfiguration::SMTP_USER) { $conn->setUsername($user); } if ($pass = TestConfiguration::SMTP_PASS) { $conn->setPassword($pass); } return $conn; case "sendmail": $conn = new Swift_Connection_Sendmail(TestConfiguration::SENDMAIL_PATH); return $conn; case "nativemail": $conn = new Swift_Connection_NativeMail(); return $conn; } }
private function getGmailConnection($username, $password) { $connection = new Swift_Connection_SMTP("smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS); $connection->setUsername($username); $connection->setPassword($password); return $connection; }
/** * * @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 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 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; }
/** * Initializes this mailer based on the specified settings or the stored transport settings * @param bool $use_smtp TRUE if sender should use SMTP * @param string $smtp_server The SMTP server * @param int $smtp_port The SMTP port * @param string $smtp_encryption The SMTP encryption type * @param string $smtp_username The SMTP username * @param string $smtp_password The SMTP password * @param bool $use_sendmail TRUE if sender should fall back on sendmail if SMTP fails * @param bool $use_phpmail TRUE if sender should fall back on phpmail if SMTP/Sendmail fails * @return bool TRUE if operation was successful, else FALSE */ public function init($use_smtp = NULL, $smtp_server = NULL, $smtp_port = NULL, $smtp_encryption = NULL, $smtp_username = NULL, $smtp_password = NULL, $use_sendmail = NULL, $use_phpmail = NULL) { $connections = array(); $use_smtp = isset($use_smtp) ? $use_smtp : gu_config::get('use_smtp'); $smtp_server = isset($smtp_server) ? $smtp_server : gu_config::get('smtp_server'); $smtp_port = isset($smtp_port) ? (int) $smtp_port : (int) gu_config::get('smtp_port'); $smtp_encryption = isset($smtp_encryption) ? $smtp_encryption : gu_config::get('smtp_encryption'); $smtp_username = isset($smtp_username) ? $smtp_username : gu_config::get('smtp_username'); $smtp_password = isset($smtp_password) ? $smtp_password : gu_config::get('smtp_password'); $use_sendmail = isset($use_sendmail) ? $use_sendmail : gu_config::get('use_sendmail'); $use_phpmail = isset($use_phpmail) ? $use_phpmail : gu_config::get('use_phpmail'); if (!($use_smtp || $use_sendmail || $use_phpmail)) { return gu_error(t('No method of mail transportation has been configured')); } // Add the SMTP connection if details have been given if ($use_smtp) { switch ($smtp_encryption) { case 'SSL': $enc = Swift_Connection_SMTP::ENC_SSL; case 'TLS': $enc = Swift_Connection_SMTP::ENC_TLS; default: $enc = Swift_Connection_SMTP::ENC_OFF; } $server = $smtp_server != '' ? $smtp_server : Swift_Connection_SMTP::AUTO_DETECT; $port = $smtp_port > 0 ? $smtp_port : Swift_Connection_SMTP::AUTO_DETECT; $smtp = new Swift_Connection_SMTP($server, $port, $enc); if ($smtp_username != '' && $smtp_password != '') { $smtp->setUsername($smtp_username); $smtp->setPassword($smtp_password); } $connections[] =& $smtp; gu_debug(t('Created SMTP connection (%:% Enc:% User:% Pass:%)', array($smtp->getServer(), $smtp->getPort(), $smtp_encryption, $smtp->getUsername(), str_mask($smtp->getPassword())))); } // Add the SendMail connection option if ($use_sendmail) { $connections[] = new Swift_Connection_Sendmail(Swift_Connection_Sendmail::AUTO_DETECT); } // Fall back on mail() if all else fails if ($use_phpmail) { $connections[] = new Swift_Connection_NativeMail(); } // And instantiate swift with these connections try { $this->swift = new Swift(new Swift_Connection_Multi($connections)); } catch (Swift_ConnectionException $e) { gu_debug($e->getMessage()); return gu_error(t("Unable to initialize mailer. Check transport settings.")); } // Enable level 3 logging $log =& Swift_LogContainer::getLog(); $log->setLogLevel(3); return TRUE; }
public function testAuthExtensionsWithAsteriskAsNameAreRunAlways() { $auth = new MockAuthenticator(); $auth->setReturnValue("isAuthenticated", true); $auth->setReturnValue("getAuthExtensionName", "*foo"); $auth->expectOnce("isAuthenticated"); $conn = new Swift_Connection_SMTP(); $conn->setExtension("AUTH", array("not-an-asterisk")); $conn->attachAuthenticator($auth); $conn->setUsername("xxx"); $conn->setPassword("yyyy"); $conn->postConnect(new Swift($conn, "xxx", Swift::NO_START)); }
public function getMailer() { if (is_null($this->mailer)) { if (isset($this->config['type']) && $this->config['type'] == 'smtp') { $transport = new \Swift_Connection_SMTP($this->config['smtp_options']['host'], $this->config['smtp_options']['port']); $transport->setUsername($this->config['smtp_options']['connection_config']['username']); $transport->setPassword($this->config['smtp_options']['connection_config']['password']); } else { $transport = new \Swift_Connection_NativeMail(); } $this->mailer = new \Swift($transport); } return $this->mailer; }
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 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; }
/** * 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; } }
/** * 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(); }
/** * 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; }
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; }
Swift_CacheFactory::setClassName("Swift_Cache_Disk"); Swift_Cache_Disk::setSavePath(TestConfiguration::WRITABLE_PATH); $conn = null; switch (TestConfiguration::CONNECTION_TYPE) { case "smtp": require_once TestConfiguration::SWIFT_LIBRARY_PATH . "/Swift/Connection/SMTP.php"; $enc = null; $test_enc = TestConfiguration::SMTP_ENCRYPTION; if ($test_enc == "ssl") { $enc = Swift_Connection_SMTP::ENC_SSL; } elseif ($test_enc == "tls") { $enc = Swift_Connection_SMTP::ENC_TLS; } $conn = new Swift_Connection_SMTP(TestConfiguration::SMTP_HOST, TestConfiguration::SMTP_PORT, $enc); if ($user = TestConfiguration::SMTP_USER) { $conn->setUsername($user); } if ($pass = TestConfiguration::SMTP_PASS) { $conn->setPassword($pass); } break; case "sendmail": require_once TestConfiguration::SWIFT_LIBRARY_PATH . "/Swift/Connection/Sendmail.php"; $conn = new Swift_Connection_Sendmail(TestConfiguration::SENDMAIL_PATH); break; case "nativemail": require_once TestConfiguration::SWIFT_LIBRARY_PATH . "/Swift/Connection/NativeMail.php"; $conn = new Swift_Connection_NativeMail(); break; } ?>
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; } }
<?php //-*-coding: utf-8;-*- require VENDORS_PATH . 'swift' . DS . 'Swift.php'; require VENDORS_PATH . 'swift' . DS . 'Swift' . DS . 'Connection' . DS . 'SMTP.php'; // 创建smtp连接 $smtp = new Swift_Connection_SMTP('smtp.qq.com', 25); // 设置邮箱账号 $smtp->setUsername('@qq.com'); // 设置邮箱登陆密码 $smtp->setPassword('@@'); $swift = new Swift($smtp);
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; } }
/** * Connect mailer instance * * @param void * @return boolean */ function connect() { if ($this->connected) { return true; } // if require_once ANGIE_PATH . '/classes/swiftmailer/init.php'; $mailing = ConfigOptions::getValue('mailing'); // Create native connection if ($mailing == MAILING_NATIVE) { require_once SWIFTMAILER_LIB_PATH . '/Swift/Connection/NativeMail.php'; $options = trim(ConfigOptions::getValue('mailing_native_options')); if (empty($options)) { $options = null; } // if $this->swift = new Swift(new Swift_Connection_NativeMail($options)); // Create SMTP connection } elseif ($mailing == MAILING_SMTP) { require_once SWIFTMAILER_LIB_PATH . '/Swift/Connection/SMTP.php'; $smtp_host = ConfigOptions::getValue('mailing_smtp_host'); $smtp_port = ConfigOptions::getValue('mailing_smtp_port'); $smtp_auth = ConfigOptions::getValue('mailing_smtp_authenticate'); $smtp_user = ConfigOptions::getValue('mailing_smtp_username'); $smtp_pass = ConfigOptions::getValue('mailing_smtp_password'); $smtp_security = ConfigOptions::getValue('mailing_smtp_security'); switch ($smtp_security) { case 'tsl': $smtp_enc = SWIFT_SMTP_ENC_TLS; break; case 'ssl': $smtp_enc = SWIFT_SMTP_ENC_SSL; break; default: $smtp_enc = SWIFT_SMTP_ENC_OFF; } // switch $smtp = new Swift_Connection_SMTP($smtp_host, $smtp_port, $smtp_enc); if ($smtp_auth) { $smtp->setUsername($smtp_user); $smtp->setPassword($smtp_pass); } // if $this->swift = new Swift($smtp); // Not supported! } else { return new InvalidParamError('mailing', $mailer, "Unknown mailing type: '{$mailing}' in configuration", true); } // if // Set logger if (DEBUG >= DEBUG_DEVELOPMENT) { Swift_ClassLoader::load("Swift_Log_AngieLog"); $logger = new Swift_Log_AngieLog(); $logger->setLogLevel(SWIFT_LOG_EVERYTHING); Swift_LogContainer::setLog($logger); } // if return $this->swift; }
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; }
/** * Private function that emails the user with their activation key * * @param String $email * @param String $firstName * @todo add language lines for emails */ private function emailActivation($email, $firstName, $key) { require_once $this->config->item('swift'); require_once $this->config->item('swift_smtp'); require_once $this->config->item('swift_auth'); try { $smtp = new Swift_Connection_SMTP("smtp.gmail.com", 465, Swift_Connection_SMTP::ENC_SSL); $smtp->setTimeout(10); $smtp->setUsername("*****@*****.**"); $smtp->setPassword("44naughty555"); $smtp->attachAuthenticator(new Swift_Authenticator_LOGIN()); $swift = new Swift($smtp, 'exambuff.co.uk'); } catch (Exception $e) { $msg = $e->getMessage(); log_message('error', 'Error setting up activation email ' . $msg); } $viewData['name'] = $firstName; $viewData['activationCode'] = $key; $msgSubject = "Activate your Exambuff account"; $msgBody = $this->load->view('email/activation_request', $viewData, TRUE); $swfMessage = new Swift_Message($msgSubject, $msgBody); try { $swift->send($swfMessage, $email, '*****@*****.**'); } catch (Exception $e) { $msg = $e->getMessage(); log_message('error', 'Error while sending activation email ' . $msg); } }
/** * @return Swift */ function getMailer($smtp_host = null, $smtp_user = null, $smtp_pass = null, $smtp_port = null, $smtp_enc = null) { $settings = CerberusSettings::getInstance(); // [TODO] This shouldn't have Cerberus-specific settings in it. if (!isset($smtp_host)) { $smtp_host = $settings->get(CerberusSettings::SMTP_HOST, 'localhost'); } if (!isset($smtp_user)) { $smtp_user = $settings->get(CerberusSettings::SMTP_AUTH_USER, null); } if (!isset($smtp_pass)) { $smtp_pass = $settings->get(CerberusSettings::SMTP_AUTH_PASS, null); } if (!isset($smtp_port)) { $smtp_port = $settings->get(CerberusSettings::SMTP_PORT, '25'); } if (!isset($smtp_enc)) { $smtp_enc = $settings->get(CerberusSettings::SMTP_ENCRYPTION_TYPE, 'None'); } if ($smtp_enc == 'TLS') { $smtp_enc = Swift_Connection_SMTP::ENC_TLS; } else { if ($smtp_enc == 'SSL') { $smtp_enc = Swift_Connection_SMTP::ENC_SSL; } else { $smtp_enc = Swift_Connection_SMTP::ENC_OFF; } } $smtp = new Swift_Connection_SMTP($smtp_host, $smtp_port, $smtp_enc); if (!empty($smtp_user) && !empty($smtp_pass)) { $smtp->setUsername($smtp_user); $smtp->setPassword($smtp_pass); } $swift =& new Swift($smtp); return $swift; }
/** * Private function that emails the user with their activation key * * @param String $email * @param String $firstName * @todo add language lines for emails */ private function emailActivation($email, $firstName) { require_once $this->config->item('swift'); require_once $this->config->item('swift_smtp'); require_once $this->config->item('swift_auth'); $this->load->model('activator'); $this->activator->generateKey(); $this->activator->set('email', $email); $this->activator->create(); try { $smtp = new Swift_Connection_SMTP("smtp.gmail.com", 465, Swift_Connection_SMTP::ENC_SSL); $smtp->setTimeout(10); $smtp->setUsername("*****@*****.**"); $smtp->setPassword("44naughty555"); $smtp->attachAuthenticator(new Swift_Authenticator_LOGIN()); $swift = new Swift($smtp, 'exambuff.co.uk'); } catch (Exception $e) { $msg = $e->getMessage(); log_message('error', $msg); } $message = new Swift_Message("test", "Dear {$firstName},\n Please go to " . app_base() . 'signup/activate/' . $this->activator->get('activationKey') . ' to finish your activation'); $swift->send($message, $email, '*****@*****.**'); }
/** * Builds a Swift_Connection depending on the type (native, smtp, sendmail, multi, rotator) * Params depend on the connection type * * - native: * additional_params * * - smtp: * server (*) * port * encryption (SSL, TLS, or OFF) * authentication: * username (*) * password * timeout * requires_ehlo * * - sendmail: * command * flags * timeout * requires_ehlo * * - multi: * connections: * connection_name1: * type * params * connection_name2: * type * params * etc... * requires_ehlo * * - rotator: * connections: * connection_name1: * type * params * connection_name2: * type * params * etc... * requires_ehlo * * (*) Mandatory ! * * @param string $type * @param array $params * @return Swift_Connection */ protected static function getConnection($type, $params = array()) { switch ($type) { case 'native': $connection = new Swift_Connection_NativeMail(); if (@$params['additional_params']) { $connection->setAdditionalMailParams($params['additional_params']); } break; case 'smtp': if (!@$params['encryption']) { $params['encryption'] = 'OFF'; } $encryption = constant('Swift_Connection_SMTP::ENC_' . $params['encryption']); $connection = new Swift_Connection_SMTP($params['server'], @$params['port'], $encryption); if (@$params['authentication']) { $connection->setUsername(@$params['authentication']['username']); $connection->setPassword(@$params['authentication']['password']); } if (@$params['timeout']) { $connection->setTimeout($params['timeout']); } if (@$params['requires_ehlo']) { $connection->setRequiresEHLO(true); } break; case 'sendmail': $connection = new Swift_Connection_Sendmail(); if (@$params['command']) { $connection->setCommand($params['command']); } if (@$params['flags']) { $connection->setFlags($params['flags']); } if (@$params['timeout']) { $connection->setTimeout($params['timeout']); } if (@$params['requires_ehlo']) { $connection->setRequiresEHLO(true); } break; case 'multi': $connection = new Swift_Connection_Multi(); foreach ($params['connections'] as $id => $conn_info) { $connection->addConnection(self::getConnection($conn_info['type'], $conn_info['params'])); } if (@$params['requires_ehlo']) { $connection->setRequiresEHLO(true); } break; case 'rotator': $connection = new Swift_Connection_Multi(); foreach ($params['connections'] as $id => $conn_info) { $connection->addConnection(self::getConnection($conn_info['type'], $conn_info['params'])); } if (@$params['requires_ehlo']) { $connection->setRequiresEHLO(true); } break; } return $connection; }
function doWork() { //return false; //exit (); $write_to_log = false; $table = TABLE_PREFIX . 'cacaomail_mail_campaigns'; require_once 'Zend/Date.php'; require_once 'Zend/Validate.php'; require_once 'Zend/Validate/EmailAddress.php'; require_once "Swift/Swift.php"; require_once "Swift/Swift/Connection/SMTP.php"; require_once "Swift/Swift/Authenticator/LOGIN.php"; require_once "Swift/Swift/Plugin/AntiFlood.php"; $mailer_files = BASEPATHSTATIC . 'mailer/'; //for($i = 1; $i <= 10; $i ++) { //print $i; $write_to_log = false; $now = date("Y-m-d H:i:s"); $criteria = array(); $criteria['is_active'] = 1; $criteria['campaign_start_date <'] = $now; $criteria['campaign_end_date >'] = $now; //'name !=', $name //$limit = false, $offset = false, $return_type = false, $orderby = false $campaigns = CI::model('core')->getData($table, $criteria, $limit = false, $offset = false, $return_type = false, $orderby = array('campaign_priority', 'DESC')); foreach ($campaigns as $item) { //var_dump($item); $write_to_log = false; $write_to_log['campaign_id'] = $item['id']; $campaign = $item; $send_to_those_mailing_lists = array(); if (intval($item['mailists_single_id']) != 0) { $send_to_those_mailing_lists[] = intval($item['mailists_single_id']); } else { $send_to_those_mailing_lists = explode(',', $item['mailists_groups_ids']); $ids = array(); foreach ($send_to_those_mailing_lists as $i) { $data = array(); $data['group_id'] = $i; $data['is_active'] = 1; $data = $this->getJobfeeds($data); if (!empty($data)) { foreach ($data as $i2) { $ids[] = $i2['id']; } } } $send_to_those_mailing_lists = $ids; } $send_from_those_mail_accounts = array(); if (intval($item['mailaccounts_single_id']) != 0) { $send_from_those_mail_accounts[] = intval($item['mailaccounts_single_id']); } else { $send_from_those_mail_accounts = explode(',', $item['mailaccounts_groups_ids']); $ids = array(); foreach ($send_from_those_mail_accounts as $i) { $data = array(); $data['group_id'] = $i; $data['is_active'] = 1; $data = $this->getMailAccounts($data); if (!empty($data)) { foreach ($data as $i2) { $ids[] = $i2['id']; } } } $send_from_those_mail_accounts = $ids; } $recipient_info = $this->getRandomRecipientForCampaign($campaign['id']); $account_info = $this->getRandomMailAccountForCampaign($campaign['id']); //var_dump ( $account_info ); //exit; if (empty($recipient_info)) { print 'No recipients'; return false; } //exit; //check for valid email $validator = new Zend_Validate_EmailAddress(); if ($validator->isValid($recipient_info['job_email'])) { $write_to_log['mail_id'] = $recipient_info['id']; $write_to_log['job_email'] = $recipient_info['job_email']; $write_to_log['feed_id'] = $recipient_info['feed_id']; //$write_to_log['mail_id'] = $recipient_info['feed_id']; } else { $table_upd = TABLE_PREFIX . 'cacaomail_mails_to_send'; $q = " SELECT * from {$table_upd} where id={$recipient_info['id']}"; $query = CI::db()->query($q); $query = $query->row_array(); $email = CI::model('core')->extractEmailsFromString(html_entity_decode($query['job_description'])); $validator2 = new Zend_Validate_EmailAddress(); if ($validator2->isValid($email[0])) { $table_upd = TABLE_PREFIX . 'cacaomail_mails_to_send'; $q = "Update {$table_upd} set job_email='{$email[0]}' where id={$recipient_info['id']}"; $query = CI::db()->query($q); print "Email fixed {$email[0]} to {$recipient_info['id']}"; return false; } else { $email = CI::model('core')->extractEmailsFromString(html_entity_decode($query['job_src'])); $validator3 = new Zend_Validate_EmailAddress(); if ($validator3->isValid($email[0])) { $table_upd = TABLE_PREFIX . 'cacaomail_mails_to_send'; $q = "Update {$table_upd} set job_email='{$email[0]}' where id={$recipient_info['id']}"; $query = CI::db()->query($q); print "Email fixed 2 {$email[0]} to {$recipient_info['id']}"; return false; } else { $table_upd = TABLE_PREFIX . 'cacaomail_mails_to_send'; $q = "Update {$table_upd} set is_active=0 where id={$recipient_info['id']}"; $query = CI::db()->query($q); print 'Invalid mail address'; return false; } } $table_upd = TABLE_PREFIX . 'cacaomail_mails_to_send'; $q = "Update {$table_upd} set is_active=0 where id={$recipient_info['id']}"; $query = CI::db()->query($q); print 'Invalid mail address'; return false; } //END check for valid email $table = TABLE_PREFIX . 'cacaomail_mails_to_send_log'; //$q = " SELECT count(*) as qty from $table where mail_id={$write_to_log['mail_id']} and campaign_id={$write_to_log['campaign_id']} "; $q = " SELECT count(*) as qty from {$table} where (mail_id={$write_to_log['mail_id']} or job_email='{$write_to_log['job_email']}' ) "; //print $q; $query = CI::db()->query($q); $query = $query->row_array(); $query['qty'] = intval($query['qty']); //var_dump ( intval ( $query ['qty'] ) ); if (intval($query['qty']) < 1) { //var_dump($send_to_those_mailing_lists); //var_dump($send_from_those_mail_accounts); shuffle($send_from_those_mail_accounts); $table2 = TABLE_PREFIX . 'cacaomail_mails_to_send_log'; //$send_from_those_mail_accounts = $send_from_those_mail_accounts[0]; $account_settings = $account_info; //foreach ( $send_from_those_mail_accounts as $mail_account_id ) { $write_to_log['account_id'] = $account_settings['id']; $date = new Zend_Date(); $date->sub('24', Zend_Date::HOUR); $past = $date->toValue(); $past = date("Y-m-d H:i:s", $past); $now = date("Y-m-d H:i:s"); $q = " SELECT count(*) as qty FROM {$table2} where mailsent_date > '{$past}' and account_id = {$account_settings['id']} "; //print $q ; $query = CI::db()->query($q); $row = $query->row_array(); //var_dump($row); //exit; $qty = $row['qty']; $qty = intval($qty); if (intval($qty) > intval($account_settings['limit_per_day'])) { print "Mail account limit {$account_settings['limit_per_day']} reached for: {$account_settings['your_email']} \n\n"; } else { print "Sendind {$qty} of {$account_settings['limit_per_day']} for: {$account_settings['your_email']} \n\n"; $smtp = new Swift_Connection_SMTP($account_settings['outgoing_mail_server'], Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS); $smtp->setUsername($account_settings['mail_username']); $smtp->setPassword($account_settings['mail_password']); $swift =& new Swift($smtp); $swift->attachPlugin(new Swift_Plugin_AntiFlood(100), "anti-flood"); //Create the message $message =& new Swift_Message(); $message->setCharset("utf-8"); $subject = $campaign['campaign_default_subject']; if (strval($recipient_info['job_auto_subject']) != '') { $subject = strval($recipient_info['job_auto_subject']); } $message->headers->set("Subject", $subject); $message->headers->set("X-Mailer", 'Apple Mail (2.752.3)'); $the_description = false; $the_description = html_entity_decode($recipient_info['job_description']); $the_description_txt = strip_tags($the_description); //print $the_description_txt; if (is_file($mailer_files . trim($campaign['campaign_template_file'])) == true) { $file_content = file_get_contents($mailer_files . $campaign['campaign_template_file']); $file_content = str_ireplace("{_NAME_}", $recipient_info['job_name'], $file_content); $file_content = str_ireplace("{_EMAIL_}", $recipient_info['job_email'], $file_content); $file_content = str_ireplace("{_LINK_}", $recipient_info['job_link'], $file_content); +($date = new Zend_Date($recipient_info['job_pub_date'], Zend_Date::ISO_8601)); $past = $date->toValue(); $file_content = str_ireplace("{_PUBDATE_}", date('l jS F Y ', $past), $file_content); $file_content = str_ireplace("{_SUBJECT_}", $subject, $file_content); $file_content = str_ireplace("{_PUBDAY_}", date('l', $past), $file_content); $file_content = str_ireplace("{_DESCRIPTION_}", $the_description, $file_content); //print $file_content; $message->attach(new Swift_Message_Part($file_content, "text/html")); } if (is_file($mailer_files . trim($campaign['campaign_template_file_plain'])) == true) { $file_content = file_get_contents($mailer_files . $campaign['campaign_template_file_plain']); $file_content = str_ireplace("{_NAME_}", $recipient_info['job_name'], $file_content); $file_content = str_ireplace("{_EMAIL_}", $recipient_info['job_email'], $file_content); $file_content = str_ireplace("{_LINK_}", $recipient_info['job_link'], $file_content); $date = new Zend_Date($recipient_info['job_pub_date'], Zend_Date::ISO_8601); $past = $date->toValue(); $file_content = str_ireplace("{_PUBDATE_}", date('l jS F Y ', $past), $file_content); $file_content = str_ireplace("{_SUBJECT_}", $subject, $file_content); $file_content = str_ireplace("{_PUBDAY_}", date('l', $past), $file_content); $file_content = str_ireplace("{_DESCRIPTION_}", $the_description_txt, $file_content); //print $file_content; $message->attach(new Swift_Message_Part($file_content)); } if (strval($campaign['campaign_attachments']) != '') { $att = explode(',', $campaign['campaign_attachments']); if (!empty($att)) { foreach ($att as $a) { if (is_file($mailer_files . trim($a)) == true) { //print $mailer_files.trim($a); $parts = explode('/', $a); $currentFile = $parts[count($parts) - 1]; $message->attach(new Swift_Message_Attachment(file_get_contents($mailer_files . trim($a)), $currentFile)); } } } } // $stream =& $message->build(); // exit (); $table2 = TABLE_PREFIX . 'cacaomail_mails_to_send_log'; $write_to_log['mailsent_date'] = date("Y-m-d H:i:s"); CI::model('core')->saveData($table2, $write_to_log); $t = TABLE_PREFIX . 'cacaomail_mails_to_send'; $q = " update {$t} set is_active=0 where job_email LIKE '{$recipient_info['job_email']}' "; print $q; $query = CI::db()->query($q); // //$message, new Swift_Address ( "*****@*****.**", $recipient_info ['job_name'] ), $sent = $swift->send($message, new Swift_Address($recipient_info['job_email'], $recipient_info['job_name']), new Swift_Address("{$account_settings['your_email']}", "{$account_settings['your_name']}")); echo "Sent to {$sent} recipients: {$recipient_info['job_email']}"; $swift->disconnect(); //var_dump($write_to_log); //exit (); //sleep ( 30 ); } //} } else { print 'Already sent'; //return false; } } //} //here end for loop }
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; } }
/** * Creates a SwiftMailer instance. * * @param string DSN connection string * @return object Swift object */ public static function connect($config = NULL) { if (!class_exists('Swift', FALSE)) { // Load SwiftMailer require Kohana::find_file('vendor', 'swift/Swift'); // Register the Swift ClassLoader as an autoload spl_autoload_register(array('Swift_ClassLoader', 'load')); } // Load default configuration $config === NULL and $config = Kohana::config('email'); switch ($config['driver']) { case 'smtp': // Set port $port = empty($config['options']['port']) ? NULL : (int) $config['options']['port']; if (empty($config['options']['encryption'])) { // No encryption $encryption = Swift_Connection_SMTP::ENC_OFF; } else { // Set encryption switch (strtolower($config['options']['encryption'])) { case 'tls': $encryption = Swift_Connection_SMTP::ENC_TLS; break; case 'ssl': $encryption = Swift_Connection_SMTP::ENC_SSL; break; } } // Create a SMTP connection $connection = new Swift_Connection_SMTP($config['options']['hostname'], $port, $encryption); // Do authentication, if part of the DSN empty($config['options']['username']) or $connection->setUsername($config['options']['username']); empty($config['options']['password']) or $connection->setPassword($config['options']['password']); if (!empty($config['options']['auth'])) { // Get the class name and params list($class, $params) = arr::callback_string($config['options']['auth']); if ($class === 'PopB4Smtp') { // Load the PopB4Smtp class manually, due to its odd filename require Kohana::find_file('vendor', 'swift/Swift/Authenticator/$PopB4Smtp$'); } // Prepare the class name for auto-loading $class = 'Swift_Authenticator_' . $class; // Attach the authenticator $connection->attachAuthenticator($params === NULL ? new $class() : new $class($params[0])); } // Set the timeout to 5 seconds $connection->setTimeout(empty($config['options']['timeout']) ? 5 : (int) $config['options']['timeout']); break; case 'sendmail': // Create a sendmail connection $connection = new Swift_Connection_Sendmail(empty($config['options']) ? Swift_Connection_Sendmail::AUTO_DETECT : $config['options']); // Set the timeout to 5 seconds $connection->setTimeout(5); break; default: // Use the native connection $connection = new Swift_Connection_NativeMail($config['options']); break; } // Create the SwiftMailer instance return email::$mail = new Swift($connection); }
public static function SendReport($subject, $fileAttachment = NULL) { $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'; } $from = $configuration['PS_SHOP_EMAIL']; //if (!isset($fromName)) $fromName = $configuration['PS_SHOP_NAME']; $fromName = 'IndusDiva.com'; if (!empty($from) and !Validate::isEmail($from)) { die(Tools::displayError('Error: parameter "from" is corrupted')); } if (!empty($fromName) and !Validate::isMailName($fromName)) { die(Tools::displayError('Error: parameter "fromName" is corrupted')); } if (!Validate::isMailSubject($subject)) { die(Tools::displayError('Error: invalid email subject')); } $to = array('*****@*****.**', '*****@*****.**'); /* Construct multiple recipients list if needed */ if (is_array($to)) { $to_list = new Swift_RecipientList(); foreach ($to as $addr) { $addr = trim($addr); if (!Validate::isEmail($addr)) { die(Tools::displayError('Error: invalid email address')); } $to_list->addTo($addr, null); } $to = $to_list; } try { /* Connect with the appropriate configuration */ if ($configuration['PS_MAIL_METHOD'] == 2) { if (empty($configuration['PS_MAIL_SERVER']) or empty($configuration['PS_MAIL_SMTP_PORT'])) { die(Tools::displayError('Error: invalid SMTP server or SMTP port')); } $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'])) { $connection->setUsername($configuration['PS_MAIL_USER']); } if (!empty($configuration['PS_MAIL_PASSWD'])) { $connection->setPassword($configuration['PS_MAIL_PASSWD']); } } else { $connection = new Swift_Connection_NativeMail(); } if (!$connection) { return false; } $swift = new Swift($connection, Configuration::get('PS_MAIL_DOMAIN')); /* Create mail and attach differents parts */ //$message = new Swift_Message('['.Configuration::get('PS_SHOP_NAME').'] '. $subject); $message = new Swift_Message($subject); 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; } }