public function testArraysCanBeAdded() { $list = new Swift_RecipientList(); $list->addTo("a@a"); $list->addTo(array("b@b", "a@a", "c@c")); $list->addTo(array(new Swift_Address("d@d", "D"), "e@e"), "E"); $this->assertEqual(array("a@a", "b@b", "c@c", "d@d", "e@e"), array_keys($list->getTo())); }
public function getMessage(array $to, $from_email, $from_name, $subject, $message_body, array $attachments, $mail_type = 'html') { $to_list = new \Swift_RecipientList(); foreach ($to as $key => $addr) { $to_list->addTo($addr); } $this->to_list = $to_list; $this->from_email = $from_email; $this->from_name = $from_name; $message = new \Swift_Message($subject, $message_body, "text/" . $mail_type); return $message; }
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(); } } }
/** * Send an email to a number of recipients * Returns the number of successful recipients, or FALSE on failure * @param mixed The recipients to send to. One of string, array, 2-dimensional array or Swift_Address * @param mixed The address to send from. string or Swift_Address * @param string The message subject * @param string The message body, optional * @return int */ public function send($recipients, $from, $subject, $body = null) { $this->addTo($recipients); $sender = false; if (is_string($from)) { $sender = $this->stringToAddress($from); } elseif ($from instanceof Swift_Address) { $sender = $from; } if (!$sender) { return false; } $this->message->setSubject($subject); if ($body) { $this->message->setBody($body); } try { if (!$this->exactCopy && !$this->recipients->getCc() && !$this->recipients->getBcc()) { $sent = $this->swift->batchSend($this->message, $this->recipients, $sender); } else { $sent = $this->swift->send($this->message, $this->recipients, $sender); } if ($this->autoFlush) { $this->flush(); } return $sent; } catch (Swift_ConnectionException $e) { $this->setError("Sending failed:<br />" . $e->getMessage()); return false; } }
/** * Send an email to a number of recipients * Returns the number of successful recipients, or FALSE on failure * @param mixed The recipients to send to. One of string, array, 2-dimensional array or Swift_Address * @param mixed The address to send from. string or Swift_Address * @param string The message subject * @param string The message body, optional * @return int */ function send($recipients, $from, $subject, $body = null) { $this->addTo($recipients); $sender = false; if (is_string($from)) { $sender = $this->stringToAddress($from); } elseif (is_a($from, "Swift_Address")) { $sender =& $from; } if (!$sender) { return false; } $this->message->setSubject($subject); if ($body) { $this->message->setBody($body); } $sent = 0; Swift_Errors::expect($e, "Swift_ConnectionException"); if (!$this->exactCopy && !$this->recipients->getCc() && !$this->recipients->getBcc()) { $sent = $this->swift->batchSend($this->message, $this->recipients, $sender); } else { $sent = $this->swift->send($this->message, $this->recipients, $sender); } if (!$e) { Swift_Errors::clear("Swift_ConnectionException"); if ($this->autoFlush) { $this->flush(); } return $sent; } $this->setError("Sending failed:<br />" . $e->getMessage()); return false; }
private function send_email($email, $subject, $content) { $swift = email::connect(); $from = '*****@*****.**'; $subject = $subject; $message = $content; if (!IN_PRODUCTION) { echo $content; } $recipients = new Swift_RecipientList(); $recipients->addTo($email); // Build the HTML message $message = new Swift_Message($subject, $message, "text/html"); $succeeded = !!$swift->send($message, $recipients, $from); $swift->disconnect(); return $succeeded; }
private function send_email($result) { // Create new password for customer $new_pass = text::random('numeric', 8); if (isset($result->member_email) && !empty($result->member_email)) { $result->member_pw = md5($new_pass); } $result->save(); //Use connect() method to load Swiftmailer $swift = email::connect(); //From, subject //$from = array($this->site['site_email'], 'Yesnotebook get password'); $from = $this->site['site_email']; $subject = 'Your Temporary Password for ' . $this->site['site_name']; //HTML message //print_r($html_content);die(); //Replate content $html_content = $this->Data_template_Model->get_value('EMAIL_FORGOTPASS'); $name = $result->member_fname . ' ' . $result->member_lname; $html_content = str_replace('#name#', $name, $html_content); if (isset($result->member_email) && !empty($result->member_email)) { $html_content = str_replace('#username#', $result->member_email, $html_content); } $html_content = str_replace('#site#', substr(url::base(), 0, -1), $html_content); $html_content = str_replace('#sitename#', $this->site['site_name'], $html_content); $html_content = str_replace('#password#', $new_pass, $html_content); $html_content = str_replace('#EmailAddress#', $this->site['site_email'], $html_content); //fwrite($fi, $html_content); //Build recipient lists $recipients = new Swift_RecipientList(); if (isset($result->member_email) && !empty($result->member_email)) { $recipients->addTo($result->member_email); } //Build the HTML message $message = new Swift_Message($subject, $html_content, "text/html"); if ($swift->send($message, $recipients, $from)) { //$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.info_mail_change_pass')); if (isset($result->member_email) && !empty($result->member_email)) { url::redirect(url::base() . 'forgotpass/thanks/' . $result->uid . '/customer'); } die; } else { } // Disconnect $swift->disconnect(); }
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; } }
/** * 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; } }
private function send_email($result) { //Use connect() method to load Swiftmailer $swift = email::connect(); //From, subject //$from = array($this->site['site_email'], 'Yesnotebook get password'); $str_random = rand(1000, 9999); $from = $this->site['site_email']; $subject = 'Forgot your password ' . $this->site['site_name']; //HTML message $path = 'application/views/email_tpl/forgotpass.tpl'; $fi = fopen($path, 'r+'); $html_content = file_get_contents($path); //Replate content $name = $result->admin_name; $html_content = str_replace('#first_name#', $name, $html_content); $html_content = str_replace('#username#', $result->admin_name, $html_content); $html_content = str_replace('#sitename#', $this->site['site_name'], $html_content); $html_content = str_replace('#password#', $str_random, $html_content); //fwrite($fi, $html_content); fclose($fi); //Build recipient lists $recipients = new Swift_RecipientList(); $recipients->addTo($result->admin_email); //Build the HTML message $message = new Swift_Message($subject, $html_content, "text/html"); if ($swift->send($message, $recipients, $from)) { $this->session->set_flash('success_msg', Kohana::lang('errormsg_lang.msg_thanks_post')); $this->db->update('admin', array('admin_pass' => md5($str_random)), array('admin_email' => $result->admin_email)); url::redirect('admin_login/forget_pass'); die; } else { } // Disconnect $swift->disconnect(); }
/** * Look for records posted by recorders who have given their email address and want to receive a summary of the record they are posting. */ private function doRecordOwnerNotifications($swift) { // Get a list of the records which contributors want to get a summary back for $emailsRequired = $this->db->select('DISTINCT occurrences.id as occurrence_id, sav2.text_value as email_address, surveys.title as survey')->from('occurrences')->join('samples', 'samples.id', 'occurrences.sample_id')->join('surveys', 'surveys.id', 'samples.survey_id')->join('sample_attribute_values as sav1', 'sav1.sample_id', 'samples.id')->join('sample_attributes as sa1', 'sa1.id', 'sav1.sample_attribute_id')->join('sample_attribute_values as sav2', 'sav2.sample_id', 'samples.id')->join('sample_attributes as sa2', 'sa2.id', 'sav2.sample_attribute_id')->where(array('sa1.caption' => 'Email me a copy of the record', 'sa2.caption' => 'Email', 'samples.created_on>=' => $this->last_run_date))->get(); // get a list of the records we need details of, so we can hit the db more efficiently. $recordsToFetch = array(); foreach ($emailsRequired as $email) { $recordsToFetch[] = $email->occurrence_id; } $occurrences = $this->db->select('o.id, ttl.taxon, s.date_start, s.date_end, s.date_type, s.entered_sref as spatial_reference, ' . 's.location_name, o.comment as sample_comment, o.comment as occurrence_comment')->from('samples as s')->join('occurrences as o', 'o.sample_id', 's.id')->join('list_taxa_taxon_lists as ttl', 'ttl.id', 'o.taxa_taxon_list_id')->in('o.id', $recordsToFetch)->get(); // Copy the occurrences to an array so we can build a structured list of data, keyed by ID $occurrenceArray = array(); foreach ($occurrences as $occurrence) { $occurrenceArray[$occurrence->id] = $occurrence; } $attrArray = array(); // Get the sample attributes $attrValues = $this->db->select('o.id, av.caption, av.value')->from('list_sample_attribute_values as av')->join('samples as s', 's.id', 'av.sample_id')->join('occurrences as o', 'o.sample_id', 's.id')->in('o.id', $recordsToFetch)->get(); foreach ($attrValues as $attrValue) { $attrArray[$attrValue->id][$attrValue->caption] = $attrValue->value; } // Get the occurrence attributes $attrValues = $this->db->select('av.occurrence_id, av.caption, av.value')->from('list_occurrence_attribute_values av')->in('av.occurrence_id', $recordsToFetch)->get(); foreach ($attrValues as $attrValue) { $attrArray[$attrValue->occurrence_id][$attrValue->caption] = $attrValue->value; } $email_config = Kohana::config('email'); foreach ($emailsRequired as $email) { $emailContent = 'Thank you for sending your record to ' . $email->survey . '. Here are the details of your contribution for your records.<br/><table>'; $this->addArrayToEmailTable($email->occurrence_id, $occurrenceArray, $emailContent); $this->addArrayToEmailTable($email->occurrence_id, $attrArray, $emailContent); $emailContent .= "</table>"; $message = new Swift_Message(kohana::lang('misc.notification_subject', kohana::config('email.server_name')), $emailContent, 'text/html'); $recipients = new Swift_RecipientList(); $recipients->addTo($email->email_address); // send the email $swift->send($message, $recipients, $email_config['address']); } }
/** * 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 function send_from_user($id = null) { $email_config = Kohana::config('email'); $this->template->title = 'Forgotten Password Email Request'; $this->template->content = new View('login/login_message'); $this->template->content->message = 'You are already logged in.<br />'; $this->template->content->link_to_home = 'YES'; $person = ORM::factory('person', $id); if (!$person->loaded) { $this->template->content->message = 'Invalid Person ID'; return; } $user = ORM::factory('user', array('person_id' => $id)); if (!$user->loaded) { $this->template->content->message = 'No user details have been set up for this Person'; return; } if (!$this->check_can_login($user)) { return; } $link_code = $this->auth->hash_password($user->username); $user->__set('forgotten_password_key', $link_code); $user->save(); try { $swift = email::connect(); $message = new Swift_Message($email_config['forgotten_passwd_title'], View::factory('templates/forgotten_password_email_2')->set(array('server' => $email_config['server_name'], 'new_password_link' => '<a href="' . url::site() . 'new_password/email/' . $link_code . '">' . url::site() . 'new_password/email/' . $link_code . '</a>')), 'text/html'); $recipients = new Swift_RecipientList(); $recipients->addTo($person->email_address, $person->first_name . ' ' . $person->surname); $swift->send($message, $recipients, $email_config['address']); } catch (Swift_Exception $e) { kohana::log('error', "Error sending forgotten password: "******"Forgotten password sent to {$person->first_name} {$person->surname}"); $this->session->set_flash('flash_info', "Forgotten password sent to {$person->first_name} {$person->surname}"); url::redirect('user'); }
/** * Run a batch send in a fail-safe manner. * This operates as Swift::batchSend() except it deals with errors itself. * @param Swift_Message To send * @param Swift_RecipientList Recipients (To: only) * @param Swift_Address The sender's address * @return int The number sent to */ public function send(Swift_Message $message, Swift_RecipientList $recipients, $sender) { $sent = 0; $successive_fails = 0; $it = $recipients->getIterator("to"); while ($it->hasNext()) { $it->next(); $recipient = $it->getValue(); $tried = 0; $loop = true; while ($loop && $tried < $this->getMaxTries()) { try { $tried++; $loop = false; $this->copyMessageHeaders($message); $sent += $n = $this->swift->send($message, $recipient, $sender); if (!$n) { $this->addFailedRecipient($recipient->getAddress()); } $successive_fails = 0; } catch (Exception $e) { $successive_fails++; $this->restoreMessageHeaders($message); if (($max = $this->getMaxSuccessiveFailures()) && $successive_fails > $max) { throw new Exception("Too many successive failures. BatchMailer is configured to allow no more than " . $max . " successive failures."); } //If an exception was thrown, give it one more go if ($t = $this->getSleepTime()) { sleep($t); } $this->forceRestartSwift(); $loop = true; } } } return $sent; }
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; } }
/** * Returns an instance of Swift_RecipientList, based on an address or an array of addresses. * * @see getSwiftAddress() * * @param $addresses * @return array of Swift_Address | Swift_RecipientList */ protected static function getSwiftAddresses($addresses, $recipient_list = false, $type = 'to') { // Detect single address $address = self::getSwiftAddress($addresses); // Single address detected if ($address instanceof Swift_Address) { $result = array($address); } else { $result = array(); foreach ($addresses as $address) { $result[] = self::getSwiftAddress($address); } } // transform into a recipient list if asked to if ($recipient_list) { $addresses = $result; $result = new Swift_RecipientList(); $result->add($addresses, null, $type); } return $result; }
/** * 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 static function sendBatch(array $emails, $subject, $message) { if (empty($subject) || empty($msg) || empty($emails)) { return false; } $obj = new self(); $from = $obj->fromEmail; $fromName = $obj->fromName; require_once SITE_ROOT . "/php/lib/Swift.php"; require_once SITE_ROOT . "/php/lib/Swift/Connection/SMTP.php"; require_once SITE_ROOT . "/php/lib/Swift/RecipientList.php"; require_once SITE_ROOT . "/php/lib/Swift/BatchMailer.php"; try { //Start Swift $swift = new Swift(new Swift_Connection_SMTP(defined('SMTP_SERVER') ? SMTP_SERVER : '127.0.0.1:25')); //Create the message $message = new Swift_Message($subject, $msg); //customize names $recips = new Swift_RecipientList(); foreach ($emails as $email) { $recips->addTo($email); } $from = new Swift_Address($from, $fromName); //Now check if Swift actually sends it if ($swift->sendBatch($message, $recips, $from)) { $log = "sent mail to: " . var_export($emails, true) . "\n"; $ret = true; } } catch (Swift_ConnectionException $e) { $ret = false; $log = "There was a problem communicating with SMTP: " . $e->getMessage() . "\n"; } catch (Swift_Message_MimeException $e) { $ret = false; $log = "There was an unexpected problem building the email:" . $e->getMessage() . "\n"; } return $ret; }
/** * Mass mailer * * @param void * @return null */ function mass_mailer() { if (!MASS_MAILER_ENABLED) { $this->httpError(HTTP_ERR_FORBIDDEN); } // if $email_data = $this->request->post('email'); $this->smarty->assign(array('email_data' => $email_data, 'exclude' => array($this->logged_user->getId()))); if ($this->request->isSubmitted()) { $errors = new ValidationErrors(); $subject = trim(array_var($email_data, 'subject')); $body = trim(array_var($email_data, 'body')); $recipient_ids = array_var($email_data, 'recipients'); if (empty($subject)) { $errors->addError(lang('Subject is required'), 'subject'); } // if if (empty($body)) { $errors->addError(lang('Body is required'), 'body'); } // if $recipients = array(); if (is_foreachable($recipient_ids)) { $recipients = Users::findByIds(array_unique($recipient_ids)); } // if if (!is_foreachable($recipients)) { $errors->addError(lang('Please select recipients'), 'recipients'); } // if if ($errors->hasErrors()) { $this->smarty->assign('errors', $errors); $this->render(); } // if $mailer =& ApplicationMailer::mailer(); $message = new Swift_Message($subject, $body, 'text/html', EMAIL_ENCODING, EMAIL_CHARSET); $recipients_list = new Swift_RecipientList(); foreach ($recipients as $recipient) { $name = $recipient->getDisplayName(); $email = $recipient->getEmail(); if ($name == $email) { $name = ''; } // if $recipients_list->add($email, $name); } // foreach $name = $this->logged_user->getDisplayName(); $email = $this->logged_user->getEmail(); if ($name == $email) { $name = ''; } // if if ($mailer->batchSend($message, $recipients_list, new Swift_Address($email, $name))) { flash_success('Email has been successfully sent'); } else { flash_error('Failed to send email'); } // if $this->redirectTo('admin_tools_mass_mailer'); } // if }
/** * Sends the specified newsletter to its recipients * @param string $recipient The recipient address * @param gu_newsletter $newsletter The newsletter to send * @param string $list_name The name of the list holding the recipient * @return bool TRUE if newsletter sent successfully, -1 if recipient failed, else FALSE */ public function send_newsletter($recipient, gu_newsletter $newsletter, $list_name = NULL) { $message = $this->create_message($newsletter, $recipient, $list_name); $recipients = new Swift_RecipientList(); $recipients->addTo($recipient); $res = $this->send($message, $recipients); return $res === 0 ? -1 : $res; }
private function send_email($record, $member, $test) { $swift = email::connect(); $from = $this->site['site_email']; $mailuser = $this->sess_cus['email']; $subject = 'Check Code ' . $this->site['site_name']; $html_content = $this->data_template_model->get_value('EMAIL_CHECKCODE_USER'); $html_content = str_replace('#date#', date('m/y/Y', strtotime('now')), $html_content); $html_content = str_replace('#username#', $this->sess_cus['name'], $html_content); $html_content = str_replace('#test#', $test['test_title'], $html_content); $html_content = str_replace('#description#', $record['description'] != '' ? '<p><strong>Description: ' . $record['description'] . '</strong></p>' : '', $html_content); $html_content = str_replace('#period#', isset($list['start_date']) && $record['start_date'] != 0 ? date('m/d/Y', $record['start_date']) : '' . (isset($list['end_date']) && $record['end_date'] != 0) ? ' ~ ' . date('m/d/Y', $record['end_date']) : 'No limit', $html_content); $html_content = str_replace('#no#', isset($record['qty']) ? $record['usage_qty'] + 1 . '/' . $record['qty'] : 'No limit', $html_content); $recipients = new Swift_RecipientList(); $recipients->addTo($this->site['site_email']); $recipients->addTo($mailuser); if (isset($record['email']) && $record['email'] != '') { $recipients->addTo($record['email']); } $message = new Swift_Message($subject, $html_content, "text/html"); if ($swift->send($message, $recipients, $from)) { } else { } // Disconnect $swift->disconnect(); }
private function _sendForwards($event, $is_inbound) { @($ticket_id = $event->params['ticket_id']); @($message_id = $event->params['message_id']); @($send_worker_id = $event->params['worker_id']); $ticket = DAO_Ticket::getTicket($ticket_id); $helpdesk_senders = CerberusApplication::getHelpdeskSenders(); $workers = DAO_Worker::getAllActive(); // [JAS]: Don't send obvious spam to watchers. if ($ticket->spam_score >= 0.9) { return true; } @($notifications = DAO_WorkerMailForward::getWhere(sprintf("%s = %d", DAO_WorkerMailForward::GROUP_ID, $ticket->team_id))); // Bail out early if we have no forwards for this group if (empty($notifications)) { return; } $message = DAO_Ticket::getMessage($message_id); $headers = $message->getHeaders(); // The whole flipping Swift section needs wrapped to catch exceptions try { $settings = CerberusSettings::getInstance(); $reply_to = $settings->get(CerberusSettings::DEFAULT_REPLY_FROM, ''); // See if we need a group-specific reply-to if (!empty($ticket->team_id)) { @($group_from = DAO_GroupSettings::get($ticket->team_id, DAO_GroupSettings::SETTING_REPLY_FROM, '')); if (!empty($group_from)) { $reply_to = $group_from; } } $sender = DAO_Address::get($message->address_id); $sender_email = strtolower($sender->email); $sender_split = explode('@', $sender_email); if (!is_array($sender_split) || count($sender_split) != 2) { return; } // If return-path is blank if (isset($headers['return-path']) && $headers['return-path'] == '<>') { return; } // Ignore bounces if ($sender_split[1] == "postmaster" || $sender_split[1] == "mailer-daemon") { return; } // Ignore autoresponses autoresponses if (isset($headers['auto-submitted']) && $headers['auto-submitted'] != 'no') { return; } // Headers //========== // Build mailing list $send_to = array(); foreach ($notifications as $n) { /* @var $n Model_WorkerMailForward */ if (!isset($n->group_id) || !isset($n->bucket_id)) { continue; } // if worker no longer exists or is disabled if (!isset($workers[$n->worker_id])) { continue; } // Don't allow a worker to usurp a helpdesk address if (isset($helpdesk_senders[$n->email])) { continue; } if ($n->group_id == $ticket->team_id && ($n->bucket_id == -1 || $n->bucket_id == $ticket->category_id)) { // Event checking if ($is_inbound && ($n->event == 'i' || $n->event == 'io') || !$is_inbound && ($n->event == 'o' || $n->event == 'io') || $is_inbound && $n->event == 'r' && $ticket->next_worker_id == $n->worker_id) { $send_to[$n->email] = true; } } } // Attachments $attachments = $message->getAttachments(); $mime_attachments = array(); if (is_array($attachments)) { foreach ($attachments as $attachment) { if (0 == strcasecmp($attachment->display_name, 'original_message.html')) { continue; } $attachment_path = APP_STORAGE_PATH . '/attachments/'; // [TODO] This is highly redundant in the codebase if (!file_exists($attachment_path . $attachment->filepath)) { continue; } $file =& new Swift_File($attachment_path . $attachment->filepath); $mime_attachments[] =& new Swift_Message_Attachment($file, $attachment->display_name, $attachment->mime_type); } } // Send copies if (is_array($send_to) && !empty($send_to)) { $mail_service = DevblocksPlatform::getMailService(); $mailer = $mail_service->getMailer(CerberusMail::getMailerDefaults()); foreach ($send_to as $to => $bool) { // Proxy the message $rcpt_to = new Swift_RecipientList(); $a_rcpt_to = array(); $mail_from = new Swift_Address($sender->email); $rcpt_to->addTo($to); $a_rcpt_to = new Swift_Address($to); $mail = $mail_service->createMessage(); /* @var $mail Swift_Message */ $mail->setTo($a_rcpt_to); $mail->setFrom($mail_from); $mail->setReplyTo($reply_to); $mail->setReturnPath($reply_to); $mail->setSubject(sprintf("[%s #%s]: %s", $is_inbound ? 'inbound' : 'outbound', $ticket->mask, $ticket->subject)); if (false !== @($msgid = $headers['message-id'])) { $mail->headers->set('Message-Id', $msgid); } if (false !== @($in_reply_to = $headers['in-reply-to'])) { $mail->headers->set('References', $in_reply_to); $mail->headers->set('In-Reply-To', $in_reply_to); } $mail->headers->set('X-Mailer', 'Cerberus Helpdesk (Build ' . APP_BUILD . ')'); $mail->headers->set('Precedence', 'List'); $mail->headers->set('Auto-Submitted', 'auto-generated'); $mail->attach(new Swift_Message_Part($message->getContent(), 'text/plain', 'base64', LANG_CHARSET_CODE)); // Send message attachments with watcher if (is_array($mime_attachments)) { foreach ($mime_attachments as $mime_attachment) { $mail->attach($mime_attachment); } } $mailer->send($mail, $rcpt_to, $mail_from); } } } catch (Exception $e) { $fields = array(DAO_MessageNote::MESSAGE_ID => $message_id, DAO_MessageNote::CREATED => time(), DAO_MessageNote::WORKER_ID => 0, DAO_MessageNote::CONTENT => 'Exception thrown while sending watcher email: ' . $e->getMessage(), DAO_MessageNote::TYPE => Model_MessageNote::TYPE_ERROR); DAO_MessageNote::create($fields); } }
private function inviteNewUser($email, $mailer) { $username = md5(rand(1000, 9999)); $password = md5(rand(1000, 9999)); $user = new sfGuardUser(); $user->username = $username; $user->password = $password; $user->groups[] = Doctrine::getTable('sfGuardGroup')->createQuery('a')->where('a.name = ?', 'leerling')->fetchOne(); $user->Profile = new sfGuardUserProfile(); $user->Profile->email = $email; $user->Profile->is_invite = true; $user->save(); $user->Profile->save(); $name = sprintf('%s (%s)', $this->getUser()->getGuardUser()->getFullname(), $this->getUser()->getUsername()); $url = $this->getController()->genUrl(sprintf('@invite_accept?username=%s', $username), true); $message = new Swift_Message(); $message->setFrom('DNS Leergemeenschap Site'); $message->setSubject('Uitnodiging DNS Leergemeenschap'); $message->setContentType('text/html'); $message->setBody("Hallo, <br /><br />\n\nJij bent door {$name} uitgenodigd om deel te nemen aan de de DNS Leergemeenschap site.<br /><br />\n\n<a href=\"{$url}\">Klik hier om de uitnodiging aan te nemen</a><br /><br /><br /><br /><br /><br />\n\n{$url}"); $recipients = new Swift_RecipientList(); foreach (sfConfig::get('app_feedback_feedback_email', array('*****@*****.**')) as $recipient) { $recipients->addTo($recipient); } $mailer->send($message, $recipients, $this->getUser()->getEmail()); }
/** * Send Email * * @param int $id_lang Language of the email (to translate the template) * @param string $template Template: the name of template not be a var but a string ! * @param string $subject * @param string $template_vars * @param string $to * @param string $to_name * @param string $from * @param string $from_name * @param array $file_attachment Array with three parameters (content, mime and name). You can use an array of array to attach multiple files * @param bool $modeSMTP * @param string $template_path * @param bool $die */ public static function Send($id_lang, $template, $subject, $template_vars, $to, $to_name = null, $from = null, $from_name = null, $file_attachment = null, $mode_smtp = null, $template_path = _PS_MAIL_DIR_, $die = false, $id_shop = null) { $theme_path = _PS_THEME_DIR_; // Get the path of theme by id_shop if exist if (is_numeric($id_shop) && $id_shop) { $shop = new Shop((int) $id_shop); $theme_name = $shop->getTheme(); if (_THEME_NAME_ != $theme_name) { $theme_path = _PS_ROOT_DIR_ . '/themes/' . $theme_name . '/'; } } $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'; } // Sending an e-mail can be of vital importance for the merchant, when his password is lost for example, so we must not die but do our best to send the e-mail if (!isset($from) || !Validate::isEmail($from)) { $from = $configuration['PS_SHOP_EMAIL']; } if (!Validate::isEmail($from)) { $from = null; } // $from_name is not that important, no need to die if it is not valid if (!isset($from_name) || !Validate::isMailName($from_name)) { $from_name = $configuration['PS_SHOP_NAME']; } if (!Validate::isMailName($from_name)) { $from_name = null; } // It would be difficult to send an e-mail if the e-mail is not valid, so this time we can die if there is a problem if (!is_array($to) && !Validate::isEmail($to)) { Tools::dieOrLog(Tools::displayError('Error: parameter "to" is corrupted'), $die); return false; } if (!is_array($template_vars)) { $template_vars = array(); } // Do not crash for this error, that may be a complicated customer name if (is_string($to_name) && !empty($to_name) && !Validate::isMailName($to_name)) { $to_name = null; } if (!Validate::isTplName($template)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail template'), $die); return false; } if (!Validate::isMailSubject($subject)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail subject'), $die); return false; } /* Construct multiple recipients list if needed */ if (is_array($to) && isset($to)) { $to_list = new Swift_RecipientList(); foreach ($to as $key => $addr) { $to_name = null; $addr = trim($addr); if (!Validate::isEmail($addr)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail address'), $die); return false; } if (is_array($to_name)) { if ($to_name && is_array($to_name) && Validate::isGenericName($to_name[$key])) { $to_name = $to_name[$key]; } } if ($to_name == null) { $to_name = $addr; } /* Encode accentuated chars */ $to_list->addTo($addr, '=?UTF-8?B?' . base64_encode($to_name) . '?='); } $to_plugin = $to[0]; $to = $to_list; } else { /* Simple recipient, one address */ $to_plugin = $to; if ($to_name == null) { $to_name = $to; } $to = new Swift_Address($to, '=?UTF-8?B?' . base64_encode($to_name) . '?='); } try { /* Connect with the appropriate configuration */ if ($configuration['PS_MAIL_METHOD'] == 2) { if (empty($configuration['PS_MAIL_SERVER']) || empty($configuration['PS_MAIL_SMTP_PORT'])) { Tools::dieOrLog(Tools::displayError('Error: invalid SMTP server or SMTP port'), $die); return false; } $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')); /* Get templates content */ $iso = Language::getIsoById((int) $id_lang); if (!$iso) { Tools::dieOrLog(Tools::displayError('Error - No ISO code for email'), $die); return false; } $template = $iso . '/' . $template; $module_name = false; $override_mail = false; // get templatePath if (preg_match('#' . __PS_BASE_URI__ . 'modules/#', $template_path) && preg_match('#modules/([a-z0-9_-]+)/#ui', $template_path, $res)) { $module_name = $res[1]; } if ($module_name !== false && (file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $template . '.txt') || file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $template . '.html'))) { $template_path = $theme_path . 'modules/' . $module_name . '/mails/'; } else { if (file_exists($theme_path . 'mails/' . $template . '.txt') || file_exists($theme_path . 'mails/' . $template . '.html')) { $template_path = $theme_path . 'mails/'; $override_mail = true; } else { if (!file_exists($template_path . $template . '.txt') || !file_exists($template_path . $template . '.html')) { Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $template . '.txt', $die); return false; } } } $template_html = file_get_contents($template_path . $template . '.html'); $template_txt = strip_tags(html_entity_decode(file_get_contents($template_path . $template . '.txt'), null, 'utf-8')); if ($override_mail && file_exists($template_path . $iso . '/lang.php')) { include_once $template_path . $iso . '/lang.php'; } else { if ($module_name && file_exists($template_path . $iso . '/lang.php')) { include_once $theme_path . 'mails/' . $iso . '/lang.php'; } else { include_once dirname(__FILE__) . '/../mails/' . $iso . '/lang.php'; } } /* Create mail and attach differents parts */ $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME') . '] ' . $subject); $message->headers->setEncoding('Q'); if (Configuration::get('PS_LOGO_MAIL') !== false && file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL'))) { $template_vars['{shop_logo}'] = $message->attach(new Swift_Message_Image(new Swift_File(_PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL')))); } else { if (file_exists(_PS_IMG_DIR_ . 'logo.jpg')) { $template_vars['{shop_logo}'] = $message->attach(new Swift_Message_Image(new Swift_File(_PS_IMG_DIR_ . Configuration::get('PS_LOGO')))); } else { $template_vars['{shop_logo}'] = ''; } } $template_vars['{shop_name}'] = Tools::safeOutput(Configuration::get('PS_SHOP_NAME')); $template_vars['{shop_url}'] = Tools::getShopDomain(true, true) . __PS_BASE_URI__ . 'index.php'; $swift->attachPlugin(new Swift_Plugin_Decorator(array($to_plugin => $template_vars)), 'decorator'); if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT) { $message->attach(new Swift_Message_Part($template_txt, 'text/plain', '8bit', 'utf-8')); } if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML) { $message->attach(new Swift_Message_Part($template_html, 'text/html', '8bit', 'utf-8')); } if ($file_attachment && !empty($file_attachment)) { // Multiple attachments? if (!is_array(current($file_attachment))) { $file_attachment = array($file_attachment); } foreach ($file_attachment as $attachment) { if (isset($attachment['content']) && isset($attachment['name']) && isset($attachment['mime'])) { $message->attach(new Swift_Message_Attachment($attachment['content'], $attachment['name'], $attachment['mime'])); } } } /* Send mail */ $send = $swift->send($message, $to, new Swift_Address($from, $from_name)); $swift->disconnect(); return $send; } catch (Swift_Exception $e) { return false; } }
/** * Send Email * * @param int $id_lang Language of the email (to translate the template) * @param string $template Template: the name of template not be a var but a string ! * @param string $subject * @param string $template_vars * @param string $to * @param string $to_name * @param string $from * @param string $from_name * @param array $file_attachment Array with three parameters (content, mime and name). You can use an array of array to attach multiple files * @param bool $modeSMTP * @param string $template_path * @param bool $die * @param string $bcc Bcc recipient */ public static function Send($id_lang, $template, $subject, $template_vars, $to, $to_name = null, $from = null, $from_name = null, $file_attachment = null, $mode_smtp = null, $template_path = _PS_MAIL_DIR_, $die = false, $id_shop = null, $bcc = 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_TYPE'), null, null, $id_shop); // Returns immediatly if emails are deactivated if ($configuration['PS_MAIL_METHOD'] == 3) { return true; } $theme_path = _PS_THEME_DIR_; // Get the path of theme by id_shop if exist if (is_numeric($id_shop) && $id_shop) { $shop = new Shop((int) $id_shop); $theme_name = $shop->getTheme(); if (_THEME_NAME_ != $theme_name) { $theme_path = _PS_ROOT_DIR_ . '/themes/' . $theme_name . '/'; } } 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'; } // Sending an e-mail can be of vital importance for the merchant, when his password is lost for example, so we must not die but do our best to send the e-mail if (!isset($from) || !Validate::isEmail($from)) { $from = $configuration['PS_SHOP_EMAIL']; } if (!Validate::isEmail($from)) { $from = null; } // $from_name is not that important, no need to die if it is not valid if (!isset($from_name) || !Validate::isMailName($from_name)) { $from_name = $configuration['PS_SHOP_NAME']; } if (!Validate::isMailName($from_name)) { $from_name = null; } // It would be difficult to send an e-mail if the e-mail is not valid, so this time we can die if there is a problem if (!is_array($to) && !Validate::isEmail($to)) { Tools::dieOrLog(Tools::displayError('Error: parameter "to" is corrupted'), $die); return false; } if (!is_array($template_vars)) { $template_vars = array(); } // Do not crash for this error, that may be a complicated customer name if (is_string($to_name) && !empty($to_name) && !Validate::isMailName($to_name)) { $to_name = null; } if (!Validate::isTplName($template)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail template'), $die); return false; } if (!Validate::isMailSubject($subject)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail subject'), $die); return false; } /* Construct multiple recipients list if needed */ $to_list = new Swift_RecipientList(); if (is_array($to) && isset($to)) { foreach ($to as $key => $addr) { $addr = trim($addr); if (!Validate::isEmail($addr)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail address'), $die); return false; } if (is_array($to_name)) { if ($to_name && is_array($to_name) && Validate::isGenericName($to_name[$key])) { $to_name = $to_name[$key]; } } if ($to_name == null || $to_name == $addr) { $to_name = ''; } else { if (function_exists('mb_encode_mimeheader')) { $to_name = mb_encode_mimeheader($to_name, 'utf-8'); } else { $to_name = self::mimeEncode($to_name); } } $to_list->addTo($addr, $to_name); } $to_plugin = $to[0]; } else { /* Simple recipient, one address */ $to_plugin = $to; if ($to_name == null || $to_name == $to) { $to_name = ''; } else { if (function_exists('mb_encode_mimeheader')) { $to_name = mb_encode_mimeheader($to_name, 'utf-8'); } else { $to_name = self::mimeEncode($to_name); } } $to_list->addTo($to, $to_name); } if (isset($bcc)) { $to_list->addBcc($bcc); } $to = $to_list; try { /* Connect with the appropriate configuration */ if ($configuration['PS_MAIL_METHOD'] == 2) { if (empty($configuration['PS_MAIL_SERVER']) || empty($configuration['PS_MAIL_SMTP_PORT'])) { Tools::dieOrLog(Tools::displayError('Error: invalid SMTP server or SMTP port'), $die); return false; } $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', null, null, $id_shop)); /* Get templates content */ $iso = Language::getIsoById((int) $id_lang); if (!$iso) { Tools::dieOrLog(Tools::displayError('Error - No ISO code for email'), $die); return false; } $template = $iso . '/' . $template; $module_name = false; $override_mail = false; // get templatePath if (preg_match('#' . __PS_BASE_URI__ . 'modules/#', str_replace(DIRECTORY_SEPARATOR, '/', $template_path)) && preg_match('#modules/([a-z0-9_-]+)/#ui', str_replace(DIRECTORY_SEPARATOR, '/', $template_path), $res)) { $module_name = $res[1]; } if ($module_name !== false && (file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $template . '.txt') || file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $template . '.html'))) { $template_path = $theme_path . 'modules/' . $module_name . '/mails/'; } elseif (file_exists($theme_path . 'mails/' . $template . '.txt') || file_exists($theme_path . 'mails/' . $template . '.html')) { $template_path = $theme_path . 'mails/'; $override_mail = true; } if (!file_exists($template_path . $template . '.txt') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT)) { Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $template . '.txt', $die); return false; } else { if (!file_exists($template_path . $template . '.html') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML)) { Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $template . '.html', $die); return false; } } $template_html = file_get_contents($template_path . $template . '.html'); $template_txt = strip_tags(html_entity_decode(file_get_contents($template_path . $template . '.txt'), null, 'utf-8')); if ($override_mail && file_exists($template_path . $iso . '/lang.php')) { include_once $template_path . $iso . '/lang.php'; } else { if ($module_name && file_exists($theme_path . 'mails/' . $iso . '/lang.php')) { include_once $theme_path . 'mails/' . $iso . '/lang.php'; } else { if (file_exists(_PS_MAIL_DIR_ . $iso . '/lang.php')) { include_once _PS_MAIL_DIR_ . $iso . '/lang.php'; } else { Tools::dieOrLog(Tools::displayError('Error - The lang file is missing for :') . ' ' . $iso, $die); return false; } } } /* Create mail and attach differents parts */ $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME', null, null, $id_shop) . '] ' . $subject); $message->setCharset('utf-8'); /* Set Message-ID - getmypid() is blocked on some hosting */ $message->setId(Mail::generateId()); $message->headers->setEncoding('Q'); if (Configuration::get('PS_LOGO_MAIL') !== false && file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop))) { $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop); } else { if (file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop))) { $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop); } else { $template_vars['{shop_logo}'] = ''; } } ShopUrl::cacheMainDomainForShop((int) $id_shop); /* don't attach the logo as */ if (isset($logo)) { $template_vars['{shop_logo}'] = $message->attach(new Swift_Message_EmbeddedFile(new Swift_File($logo), null, ImageManager::getMimeTypeByExtension($logo))); } if (Context::getContext()->link instanceof Link === false) { Context::getContext()->link = new Link(); } $template_vars['{shop_name}'] = Tools::safeOutput(Configuration::get('PS_SHOP_NAME', null, null, $id_shop)); $template_vars['{shop_url}'] = Context::getContext()->link->getPageLink('index', true, Context::getContext()->language->id); $template_vars['{my_account_url}'] = Context::getContext()->link->getPageLink('my-account', true, Context::getContext()->language->id); $template_vars['{guest_tracking_url}'] = Context::getContext()->link->getPageLink('guest-tracking', true, Context::getContext()->language->id); $template_vars['{history_url}'] = Context::getContext()->link->getPageLink('history', true, Context::getContext()->language->id); $template_vars['{color}'] = Tools::safeOutput(Configuration::get('PS_MAIL_COLOR', null, null, $id_shop)); $swift->attachPlugin(new Swift_Plugin_Decorator(array($to_plugin => $template_vars)), 'decorator'); if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT) { $message->attach(new Swift_Message_Part($template_txt, 'text/plain', '8bit', 'utf-8')); } if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML) { $message->attach(new Swift_Message_Part($template_html, 'text/html', '8bit', 'utf-8')); } if ($file_attachment && !empty($file_attachment)) { // Multiple attachments? if (!is_array(current($file_attachment))) { $file_attachment = array($file_attachment); } foreach ($file_attachment as $attachment) { if (isset($attachment['content']) && isset($attachment['name']) && isset($attachment['mime'])) { $message->attach(new Swift_Message_Attachment($attachment['content'], $attachment['name'], $attachment['mime'])); } } } /* Send mail */ $send = $swift->send($message, $to, new Swift_Address($from, $from_name)); $swift->disconnect(); ShopUrl::resetMainDomainCache(); return $send; } catch (Swift_Exception $e) { return false; } }
private function send_email($record) { //Use connect() method to load Swiftmailer $swift = email::connect(); //From, subject $from = $this->site['site_email']; $subject = 'Testing ' . $this->site['site_name']; //HTML message $html_content = Data_template_Model::get_value('EMAIL_TESTING'); //Replate content if (isset($this->sess_cus['name']) && !empty($this->sess_cus['name'])) { $name = $this->sess_cus['name']; } else { $name = $this->sess_cus['email']; } $html_content = str_replace('#name#', $name, $html_content); $test = $this->test_model->get($record['test_uid']); $html_content = str_replace('#test#', $test['test_title'], $html_content); $html_content = str_replace('#date#', $this->format_int_date($record['testing_date'], $this->site['site_short_date']), $html_content); $html_content = str_replace('#score#', $record['testing_score'], $html_content); $html_content = str_replace('#duration#', gmdate("H:i:s", $record['duration']), $html_content); $html_content = str_replace('#code#', $record['testing_code'], $html_content); $html_content = str_replace('#site#', $this->site['site_name'], $html_content); //Build recipient lists $recipients = new Swift_RecipientList(); $recipients->addTo($this->sess_cus['email']); //$recipients->addTo($this->site['site_email']); //Build the HTML message $message = new Swift_Message($subject, $html_content, "text/html"); if ($swift->send($message, $recipients, $from)) { } else { } // Disconnect $swift->disconnect(); }
/** * Save the results of a configuration of emails form, unless the skip button was clicked * in which case the user is redirected to a page allowing them to confirm this. */ public function config_email_save() { if (isset($_POST['skip'])) { url::redirect('setup_check/skip_email'); } else { $source = dirname(dirname(__FILE__)) . '/config_files/_email.php'; $dest = dirname(dirname(dirname(dirname(__FILE__)))) . "/application/config/email.php"; try { unlink($dest); } catch (Exception $e) { // file doesn't exist?' } try { $_source_content = file_get_contents($source); // Now save the POST form values into the config file foreach ($_POST as $field => $value) { $_source_content = str_replace("*{$field}*", $value, $_source_content); } file_put_contents($dest, $_source_content); // Test the email config $swift = email::connect(); $message = new Swift_Message('Setup test', Kohana::lang('setup.test_email_title'), 'text/html'); $recipients = new Swift_RecipientList(); $recipients->addTo($_POST['test_email']); if ($swift->send($message, $recipients, $_POST['address']) == 1) { $_source_content = str_replace("*test_result*", 'pass', $_source_content); file_put_contents($dest, $_source_content); url::redirect('setup_check'); } else { $this->error = Kohana::lang('setup.test_email_failed'); $this->config_email(); } } catch (Exception $e) { // Swift mailer messages tend to have the error message as the last part, with each part colon separated. $msg = explode(':', $e->getMessage()); $this->error = $msg[count($msg) - 1]; kohana::log('error', $e->getMessage()); $this->config_email(); } } }
/** * Send a message to any number of recipients * @param Swift_Message The message to send. This does not need to (and shouldn't really) have any of the recipient headers set. * @param mixed The recipients to send to. Can be a string, Swift_Address or Swift_RecipientList. Note that all addresses apart from Bcc recipients will appear in the message headers * @param mixed The address to send the message from. Can either be a string or an instance of Swift_Address. * @return int The number of successful recipients * @throws Swift_ConnectionException If sending fails for any reason. */ public function send(Swift_Message $message, $recipients, $from) { Swift_ClassLoader::load("Swift_Message_Encoder"); if (is_string($recipients) && preg_match("/^" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . "\$/", $recipients)) { $recipients = new Swift_Address($recipients); } elseif (!$recipients instanceof Swift_AddressContainer) { throw new Exception("The recipients parameter must either be a valid string email address, " . "an instance of Swift_RecipientList or an instance of Swift_Address."); } if (is_string($from) && preg_match("/^" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . "\$/", $from)) { $from = new Swift_Address($from); } elseif (!$from instanceof Swift_Address) { throw new Exception("The sender parameter must either be a valid string email address or " . "an instance of Swift_Address."); } $log = Swift_LogContainer::getLog(); if (!$message->getEncoding() && !$this->connection->hasExtension("8BITMIME")) { $message->setEncoding("QP", true, true); } $list = $recipients; if ($recipients instanceof Swift_Address) { $list = new Swift_RecipientList(); $list->addTo($recipients); } Swift_ClassLoader::load("Swift_Events_SendEvent"); $send_event = new Swift_Events_SendEvent($message, $list, $from, 0); $this->notifyListeners($send_event, "BeforeSendListener"); $to = $cc = array(); if (!($has_from = $message->getFrom())) { $message->setFrom($from); } if (!($has_return_path = $message->getReturnPath())) { $message->setReturnPath($from->build(true)); } if (!($has_reply_to = $message->getReplyTo())) { $message->setReplyTo($from); } if (!$has_reply_to[0]) { $message->setReplyTo($from->getAddress()); } if (!($has_message_id = $message->getId())) { $message->generateId(); } $this->command("MAIL FROM: " . $message->getReturnPath(true), 250); $failed = 0; $sent = 0; $tmp_sent = 0; $it = $list->getIterator("to"); while ($it->hasNext()) { $it->next(); $address = $it->getValue(); $to[] = $address->build(); try { $this->command("RCPT TO: " . $address->build(true), 250); $tmp_sent++; } catch (Swift_BadResponseException $e) { $failed++; $send_event->addFailedRecipient($address->getAddress()); if ($log->hasLevel(Swift_Log::LOG_FAILURES)) { $log->addfailedRecipient($address->getAddress()); } } } $it = $list->getIterator("cc"); while ($it->hasNext()) { $it->next(); $address = $it->getValue(); $cc[] = $address->build(); try { $this->command("RCPT TO: " . $address->build(true), 250); $tmp_sent++; } catch (Swift_BadResponseException $e) { $failed++; $send_event->addFailedRecipient($address->getAddress()); if ($log->hasLevel(Swift_Log::LOG_FAILURES)) { $log->addfailedRecipient($address->getAddress()); } } } if ($failed == count($to) + count($cc)) { $this->reset(); $this->notifyListeners($send_event, "SendListener"); return 0; } if (!($has_to = $message->getTo()) && !empty($to)) { $message->setTo($to); } if (!($has_cc = $message->getCc()) && !empty($cc)) { $message->setCc($cc); } $this->command("DATA", 354); $data = $message->build(); while (false !== ($bytes = $data->read())) { $this->command($bytes, -1); } if ($log->hasLevel(Swift_Log::LOG_NETWORK)) { $log->add("<MESSAGE DATA>", Swift_Log::COMMAND); } try { $this->command("\r\n.", 250); $sent += $tmp_sent; } catch (Swift_BadResponseException $e) { $failed += $tmp_sent; } $tmp_sent = 0; $has_bcc = $message->getBcc(); $it = $list->getIterator("bcc"); while ($it->hasNext()) { $it->next(); $address = $it->getValue(); if (!$has_bcc) { $message->setBcc($address->build()); } try { $this->command("MAIL FROM: " . $message->getReturnPath(true), 250); $this->command("RCPT TO: " . $address->build(true), 250); $this->command("DATA", 354); $data = $message->build(); while (false !== ($bytes = $data->read())) { $this->command($bytes, -1); } if ($log->hasLevel(Swift_Log::LOG_NETWORK)) { $log->add("<MESSAGE DATA>", Swift_Log::COMMAND); } $this->command("\r\n.", 250); $sent++; } catch (Swift_BadResponseException $e) { $failed++; $send_event->addFailedRecipient($address->getAddress()); if ($log->hasLevel(Swift_Log::LOG_FAILURES)) { $log->addfailedRecipient($address->getAddress()); } $this->reset(); } } $total = count($to) + count($cc) + count($list->getBcc()); $send_event->setNumSent($sent); $this->notifyListeners($send_event, "SendListener"); if (!$has_return_path) { $message->setReturnPath(""); } if (!$has_from) { $message->setFrom(""); } if (!$has_to) { $message->setTo(""); } if (!$has_reply_to) { $message->setReplyTo(null); } if (!$has_cc) { $message->setCc(null); } if (!$has_bcc) { $message->setBcc(null); } if (!$has_message_id) { $message->setId(null); } if ($log->hasLevel(Swift_Log::LOG_NETWORK)) { $log->add("Message sent to " . $sent . "/" . $total . " recipients", Swift_Log::NORMAL); } return $sent; }
public static function Send($id_lang, $template, $subject, $templateVars, $to, $toName = NULL, $from = NULL, $fromName = NULL, $fileAttachment = NULL, $modeSMTP = NULL, $templatePath = _PS_MAIL_DIR_, $die = false) { $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)) { Tools::dieOrLog(Tools::displayError('Error: parameter "from" is corrupted'), $die); return false; } if (!empty($fromName) and !Validate::isMailName($fromName)) { Tools::dieOrLog(Tools::displayError('Error: parameter "fromName" is corrupted'), $die); return false; } if (!is_array($to) and !Validate::isEmail($to)) { Tools::dieOrLog(Tools::displayError('Error: parameter "to" is corrupted'), $die); return false; } if (!is_array($templateVars)) { Tools::dieOrLog(Tools::displayError('Error: parameter "templateVars" is not an array'), $die); return false; } // Do not crash for this error, that may be a complicated customer name if (is_string($toName)) { if (!empty($toName) and !Validate::isMailName($toName)) { $toName = NULL; } } if (!Validate::isTplName($template)) { Tools::dieOrLog(Tools::displayError('Error: invalid email template'), $die); return false; } if (!Validate::isMailSubject($subject)) { Tools::dieOrLog(Tools::displayError('Error: invalid email subject'), $die); return false; } /* Construct multiple recipients list if needed */ if (is_array($to) and isset($to)) { $to_list = new Swift_RecipientList(); foreach ($to as $key => $addr) { $to_name = NULL; $addr = trim($addr); if (!Validate::isEmail($addr)) { Tools::dieOrLog(Tools::displayError('Error: invalid email address'), $die); return false; } if (is_array($toName)) { 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 ($configuration['PS_MAIL_METHOD'] == 2) { if (empty($configuration['PS_MAIL_SERVER']) or empty($configuration['PS_MAIL_SMTP_PORT'])) { Tools::dieOrLog(Tools::displayError('Error: invalid SMTP server or SMTP port'), $die); return false; } $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')); /* Get templates content */ $iso = Language::getIsoById((int) $id_lang); if (!$iso) { Tools::dieOrLog(Tools::displayError('Error - No ISO code for email'), $die); return false; } $template = $iso . '/' . $template; $moduleName = false; $overrideMail = false; // get templatePath if (preg_match('#' . __PS_BASE_URI__ . 'modules/#', $templatePath) and preg_match('#modules/([a-z0-9_-]+)/#ui', $templatePath, $res)) { $moduleName = $res[1]; } if ($moduleName !== false and (file_exists(_PS_THEME_DIR_ . 'modules/' . $moduleName . '/mails/' . $template . '.txt') or file_exists(_PS_THEME_DIR_ . 'modules/' . $moduleName . '/mails/' . $template . '.html'))) { $templatePath = _PS_THEME_DIR_ . 'modules/' . $moduleName . '/mails/'; } elseif (file_exists(_PS_THEME_DIR_ . 'mails/' . $template . '.txt') or file_exists(_PS_THEME_DIR_ . 'mails/' . $template . '.html')) { $templatePath = _PS_THEME_DIR_ . 'mails/'; $overrideMail = true; } elseif (!file_exists($templatePath . $template . '.txt') or !file_exists($templatePath . $template . '.html')) { Tools::dieOrLog(Tools::displayError('Error - The following email template is missing:') . ' ' . $templatePath . $template . '.txt', $die); return false; } $templateHtml = file_get_contents($templatePath . $template . '.html'); $templateTxt = strip_tags(html_entity_decode(file_get_contents($templatePath . $template . '.txt'), NULL, 'utf-8')); if ($overrideMail and file_exists($templatePath . $iso . '/lang.php')) { include_once $templatePath . $iso . '/lang.php'; } elseif ($moduleName and file_exists($templatePath . $iso . '/lang.php')) { include_once _PS_THEME_DIR_ . 'mails/' . $iso . '/lang.php'; } else { include_once dirname(__FILE__) . '/../mails/' . $iso . '/lang.php'; } /* Create mail and attach differents parts */ $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME') . '] ' . $subject); $templateVars['{shop_logo}'] = file_exists(_PS_IMG_DIR_ . 'logo_mail.jpg') ? $message->attach(new Swift_Message_Image(new Swift_File(_PS_IMG_DIR_ . 'logo_mail.jpg'))) : (file_exists(_PS_IMG_DIR_ . 'logo.jpg') ? $message->attach(new Swift_Message_Image(new Swift_File(_PS_IMG_DIR_ . 'logo.jpg'))) : ''); $templateVars['{shop_name}'] = Tools::safeOutput(Configuration::get('PS_SHOP_NAME')); $templateVars['{shop_url}'] = Tools::getShopDomain(true, true) . __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; } }