/**
  * Send mail using Mandrill (by MailChimp)
  *
  * @param \Cake\Network\Email\Email $email Cake Email
  * @return array
  */
 public function send(Email $email)
 {
     $this->transportConfig = Hash::merge($this->transportConfig, $this->_config);
     // Initiate a new Mandrill Message parameter array
     $message = ['html' => $email->message(\Cake\Network\Email\Email::MESSAGE_HTML), 'text' => $email->message(\Cake\Network\Email\Email::MESSAGE_TEXT), 'subject' => $this->_decode($email->subject()), 'from_email' => key($email->from()), 'from_name' => current($email->from()), 'to' => [], 'headers' => ['Reply-To' => is_null(key($email->replyTo())) ? key($email->from()) : key($email->replyTo())], 'recipient_metadata' => [], 'attachments' => [], 'images' => []];
     // Merge Mandrill Parameters
     $message = array_merge($message, Hash::merge($this->defaultParameters, $email->profile()['Mandrill']));
     // Add receipients
     foreach (['to', 'cc', 'bcc'] as $type) {
         foreach ($email->{$type}() as $mail => $name) {
             $message['to'][] = ['email' => $mail, 'name' => $name, 'type' => $type];
         }
     }
     // Attachments
     $message = $this->_attachments($email, $message);
     // Create a new scoped Http Client
     $this->http = new Client(['host' => 'mandrillapp.com', 'scheme' => 'https', 'headers' => ['User-Agent' => 'CakePHP Mandrill Plugin']]);
     // Sending as a template? Then in case we find mail content, we add this as a 'template_content'.
     // In you Mandrill template, use <div mc:edit="content"></div> to get the contents of your email
     if (!is_null($message['template_name']) && $message['html']) {
         if (!isset($message['template_content']) || !is_array($message['template_content'])) {
             $message['template_content'] = [];
         }
         $message['template_content'][] = ['name' => 'content', 'content' => $message['html']];
     }
     // Are we sending a template?
     if (!is_null($message['template_name']) && !empty($message['template_content'])) {
         return $this->_sendTemplate($message, $this->transportConfig['async'], $this->transportConfig['ip_pool'], $message['send_at']);
     } else {
         return $this->_send($message, $this->transportConfig['async'], $this->transportConfig['ip_pool'], $message['send_at']);
     }
 }
 public function emailToManager()
 {
     //$this->out('Hello Manager');
     $email = new Email('default');
     $email->from(['*****@*****.**' => 'Administrator dimanamacet.com'])->to('*****@*****.**')->subject('Daily Activity')->send('Lorem Ipsum DOlor sit Amet');
     $this->out('Success');
 }
Ejemplo n.º 3
0
 /**
  * Prepares the `from` email address.
  *
  * @return array
  */
 protected function _prepareFromAddress()
 {
     $from = $this->_cakeEmail->returnPath();
     if (empty($from)) {
         $from = $this->_cakeEmail->from();
     }
     return $from;
 }
Ejemplo n.º 4
0
 public function afterForgot($event, $user)
 {
     $email = new Email('default');
     $email->viewVars(['user' => $user, 'resetUrl' => Router::fullBaseUrl() . Router::url(['prefix' => false, 'plugin' => 'Users', 'controller' => 'Users', 'action' => 'reset', $user['email'], $user['request_key']]), 'baseUrl' => Router::fullBaseUrl(), 'loginUrl' => Router::fullBaseUrl() . '/login']);
     $email->from(Configure::read('Users.email.from'));
     $email->subject(Configure::read('Users.email.afterForgot.subject'));
     $email->emailFormat('both');
     $email->transport(Configure::read('Users.email.transport'));
     $email->template('Users.afterForgot', 'Users.default');
     $email->to($user['email']);
     $email->send();
 }
Ejemplo n.º 5
0
 protected function _execute(array $data)
 {
     $email = new Email('default');
     $email->template("devis");
     $email->emailFormat("both");
     $email->viewVars($data);
     $email->from(["*****@*****.**" => "Contact Reno Patrimoine"]);
     $email->to("*****@*****.**");
     $email->subject("Demande de devis: " . $data["prenom"] . " " . $data["nom"]);
     $email->send();
     return true;
 }
Ejemplo n.º 6
0
 public function dadosAtualizados()
 {
     $users = $ldap->getUsers("uid=*");
     $emails = array();
     foreach ($users as $user) {
         $email = $user['uid'][0] . '@smt.ufrj.br';
         array_push($emails, $email);
     }
     $email = new Email('gmail');
     $email->from(['*****@*****.**' => 'Controle de Usuarios'])->emailFormat('html')->to($emails)->subject('Notificação SMT')->send('Favor manter seus dados atualizados.');
     $aviso = new Email('gmail');
     $aviso->from(['*****@*****.**' => 'Controle de Usuarios'])->emailFormat('html')->to('*****@*****.**')->subject('JOB Realizado')->send('Job Dados Atualizados executado com sucesso.');
 }
Ejemplo n.º 7
0
 protected function _execute(array $data)
 {
     //print_r($data); exit;
     if (null != $data['email']) {
         $adminEmail = "*****@*****.**";
         //EMAIL THE Admin
         $subject = __('A new form submission been received from the MarketingConneX.com Challenges landing page');
         $email = new Email('default');
         $email->sender($data['email'], $data['firstname']);
         $email->from([$data['email'] => $data['firstname']])->to([$adminEmail => 'marketingconneX.com'])->subject($subject)->emailFormat('html')->template('landingpageform')->viewVars(array('firstname' => $data['firstname'], 'lastname' => $data['lastname'], 'email' => $data['email'], 'website' => $data['website'], 'phone' => $data['phone'], 'info' => $data['info'], 'landingpage' => $data['landingpage']))->send();
         return true;
     }
     return false;
 }
Ejemplo n.º 8
0
 protected function _execute(array $data)
 {
     //print_r($data); exit;
     if (null != $data['email']) {
         //SEND TO SALES FORCE
         //-----------------------------------
         //then bundle the request and send it to Salesforce.com
         $req = "&lead_source=" . "Web";
         $req .= "&first_name=" . $data['firstname'];
         $req .= "&last_name=" . $data['lastname'];
         $req .= "&company=" . $data['company'];
         $req .= "&00N20000009ZAQB=" . $data['position'];
         $req .= "&email=" . $data['email'];
         $req .= "&phone=" . $data['phone'];
         $req .= "&debug=" . urlencode("0");
         $req .= "&oid=" . urlencode("00D20000000ozqG");
         $req .= "&retURL=" . urlencode("http://qa.marketingconnex.com/pages/thank-you");
         $req .= "&debugEmail=" . urlencode("*****@*****.**");
         $header = "POST /servlet/servlet.WebToLead?encoding=UTF-8 HTTP/1.0\r\n";
         $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
         $header .= "Host: www.salesforce.com\r\n";
         $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
         $fp = fsockopen('www.salesforce.com', 80, $errno, $errstr, 30);
         if (!$fp) {
             echo "No connection made";
         } else {
             fputs($fp, $header . $req);
             while (!feof($fp)) {
                 $res = fgets($fp, 1024);
                 //echo $res;
             }
         }
         fclose($fp);
         //-----------------------------------
         $adminEmail = "*****@*****.**";
         //EMAIL THE CUSTOMER
         $subject = __('Thank you for contacting MarketingConneX.com');
         $email = new Email('default');
         $email->sender($adminEmail, 'marketingconneX.com');
         $email->from([$adminEmail => 'marketingconneX.com'])->to([$data['email'] => $data['name']])->subject($subject)->emailFormat('html')->template('contactform', 'system')->viewVars(array('email_type' => 'customer', 'name' => $data['firstname'], 'company' => $data['company'], 'position' => $data['position'], 'email' => $data['email'], 'site_url' => 'http://www.marketingconnex.com', 'SITE_NAME' => 'MarketingConneX.com', 'phone' => $data['phone'], 'info' => $data['info'], 'message' => $data['message']))->send();
         //EMAIL THE Admin
         $subject = __('A new enquiry has been received on MarketingConneX.com');
         $email = new Email('default');
         $email->sender($adminEmail, 'marketingconneX.com');
         $email->from([$data['email'] => $data['name']])->to([$adminEmail => 'marketingconneX.com'])->subject($subject)->emailFormat('html')->template('contactform', 'system')->viewVars(array('email_type' => 'admin', 'name' => $data['firstname'], 'company' => $data['company'], 'position' => $data['position'], 'email' => $data['email'], 'site_url' => 'http://www.marketingconnex.com', 'SITE_NAME' => 'MarketingConneX.com', 'phone' => $data['phone'], 'info' => $data['info'], 'message' => $data['message']))->send();
         return true;
     }
     return false;
 }
 public function email()
 {
     if ($this->request->is('get')) {
         $userId = $this->Auth->user('id');
         $username = $this->Auth->user('username');
         $this->loadModel('UserTypes');
         $userTypes = $this->UserTypes->listSubCategories();
         $this->set(compact('userId', 'username', 'userTypes'));
     } else {
         if ($this->request->is('post')) {
             Email::configTransport('gmail', ['host' => 'smtp.gmail.com', 'port' => 587, 'username' => '*****@*****.**', 'password' => 'mustang996', 'className' => 'Smtp', 'tls' => true]);
             $email = new Email();
             $email->transport('gmail');
             $email->from(['*****@*****.**' => 'Store Site'])->to('*****@*****.**')->emailFormat('html')->subject(FormatContactForm::getSubject($this->request->data['subject'], ['suffix' => ' | Store Site']))->send(FormatContactForm::getMessage($this->request->data, ['uppercaseLabel' => true]));
             return $this->redirect(['controller' => 'CustomStaticPages', 'action' => 'index']);
         }
     }
 }
Ejemplo n.º 10
0
 /**
  * TestSend method
  *
  * @return void
  */
 public function testSendWithEmail()
 {
     $Email = new Email();
     $Email->from('*****@*****.**', 'CakePHP Test');
     $Email->to('*****@*****.**', 'CakePHP');
     $Email->cc(['*****@*****.**' => 'Mark Story', '*****@*****.**' => 'Juan Basso']);
     $Email->bcc('*****@*****.**');
     $Email->subject('Testing Message');
     $Email->transport('queue');
     $config = $Email->config('default');
     $this->QueueTransport->config($config);
     $result = $this->QueueTransport->send($Email);
     $this->assertEquals('Email', $result['jobtype']);
     $this->assertTrue(strlen($result['data']) < 10000);
     $output = unserialize($result['data']);
     //debug($output);
     //$this->assertEquals($Email, $output['settings']);
 }
Ejemplo n.º 11
0
 public function contact()
 {
     $this->set('title_for_layout', 'Contact');
     if ($this->request->is('post')) {
         if ($this->request->data['captcha'] != $_SESSION['captcha']) {
             $this->Flash->error(__('Please enter correct captcha code and try again.', true));
         } else {
             //SEND EMAIL
             $email = new Email();
             $email->transport('default');
             $email->from([$this->request->data['email'] => $this->request->data['name']])->to(Configure::read('cakeblog_contact_email'))->subject('Website Contact - ' . $this->request->data['type'])->send($this->request->data['message']);
             $this->Flash->success(__('Your message has been submitted'));
             return $this->redirect("" . Configure::read('BASE_URL') . "/contact");
         }
     }
     //RENDER THEME VIEW
     $this->render('' . Configure::read('cakeblog_theme') . '.contact');
 }
 public function sendMail($to, $subject, $from, $message, $attachments = null, $emailCofig = 'default', $emailtemplate = 'default', $formate = 'html', $replyto = null, $cc = null, $bcc = null)
 {
     $email = new Email('default');
     $email->emailFormat($formate);
     $email->from(array($from => Configure::read('FROM_EMAIL_NAME')));
     $email->to($to);
     $email->cc($cc);
     $email->bcc($bcc);
     $email->replyTo($replyto);
     $email->subject($subject);
     $email->template($emailtemplate, 'default');
     //        $email->attachments($attachments);
     if ($email->send($message)) {
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 13
0
 private function _generateEmails($loggedUser = null, $OrderingCustomer = null, $orderTotal = null, $order = null, $shopcart = null)
 {
     //choose to send email for new orders from here as well. with item list, customer details,
     //send an email to rick letting him know that an order was placed.
     //Send email to customer with their new reset password hashed link/url
     //create email object and set email config settings
     $orderEmail = new Email('default');
     $orderEmail->transport('default');
     //set the type of email format and use our custom template.
     $orderEmail->emailFormat('html');
     $orderEmail->template('order_email');
     //Set the email headers.
     $orderEmail->from(['*****@*****.**' => 'Solemate Doormats Web Orders']);
     $orderEmail->sender(['*****@*****.**' => 'Solemate Doormats inc']);
     $orderEmail->replyTo('*****@*****.**');
     $fullOrderUrl = Router::url(array('controller' => 'Orders', 'action' => 'view', $order->id), true);
     //send the administrator order created email with listing of items, weights, totals etc
     //set the email to send to
     $orderEmail->to(Configure::read('orderRecievedEmail'));
     $orderEmail->subject('Solemate Order has been placed on ' . date("Y-m-d"));
     $message = "<table id='orderEmailTable' style='border: 1'><tr><th>Item Name</th><th>Item Cost (per Unit)</th><th>Base Weight (per Unit)</th>";
     $message .= "<th>Total Wieght Ordered</th><th>Number of Bales</th></tr>";
     foreach ($shopcart as $item) {
         $message .= "<tr><td>" . $item['item_name'] . "</td>" . "<td>" . $item['base_price'] . "</td><td>" . $item['matt_weight'];
         $message .= "</td><td>" . h($item['matt_weight'] * $item['_joinData']['quantity']) . "</td><td>" . h($item['_joinData']['quantity'] / $item['matt_bale_count']) . "</td>";
     }
     $message .= "</tr></table>";
     //send email with body message of
     $orderEmail->send('Hi there Solemate Admin, this is an automated email to let you know a new order has been placed on the website ordering system,' . ' the order id is ' . $order->id . '. The customer placing the order was ' . $OrderingCustomer['first_name'] . ' ' . $OrderingCustomer['last_name'] . ', and was placed by the user: '******'username'] . ' who has the role of ' . $this->request->session()->read('userRole') . ' user type. ' . ' The url to view to this order is <a href="' . $fullOrderUrl . '">' . $OrderingCustomer['first_name'] . ' ' . $OrderingCustomer['last_name'] . '\'s New Order</a> you will need to log in if you have not already done so recently. The invoice total will be (inc GST)$' . $orderTotal . '<br />' . $message);
     //set the email touser letting them know of their order items and total.
     $orderEmail1 = new Email('default');
     $orderEmail1->transport('default');
     //set the type of email format and use our custom template.
     $orderEmail1->emailFormat('html');
     $orderEmail1->template('order_email');
     //Set the email headers.
     $orderEmail1->from(['*****@*****.**' => 'Solemate Doormats Web Orders']);
     $orderEmail1->sender(['*****@*****.**' => 'Solemate Doormats inc']);
     $orderEmail1->replyTo('*****@*****.**');
     $orderEmail1->to($loggedUser['email']);
     $orderEmail1->subject('Your Solemate Order was placed on ' . date("Y-m-d"));
     //send email with body message of
     $orderEmail1->send('Hi there ' . $loggedUser['username'] . ', this is an automated email to let you know your order has been placed on the Solemate ordering system and our sales team will be in touch with the invoice and payment details.' . '<br />Order id is ' . $order->id . ', and was placed by the user: '******'username'] . ' who has the role of ' . $this->request->session()->read('userRole') . ' user type. ' . ' The url to view to view details of this order is <a href="' . $fullOrderUrl . '">' . $OrderingCustomer['first_name'] . ' ' . $OrderingCustomer['last_name'] . '\'s New Order</a> you will need to log in if you have not already done so recently. The invoice total will be (inc GST)' . $orderTotal . '.');
     return true;
 }
 public function report($id = null)
 {
     $resource = $this->Resources->get($id, ['contain' => ['Folders', 'Users', 'Vendors']]);
     if ($this->request->is(['post', 'put'])) {
         $users = $this->Users->find()->where(['role' => 'admin', 'status' => 'Y']);
         foreach ($users as $user) {
             $admins[] = $user->email;
         }
         $msg = "\nFile ID: {$resource->id}<br />\nFile: {$resource->sourcepath}<br />\nOwner: {$resource->user->username}<br />\nVendor: {$resource->vendor->company_name}<br />\nFile URL: {$resource->publicurl}<br />\n<br />\n            ";
         $msg .= $this->request->data['message'];
         $fgemail = new Email('default');
         $fgemail->sender($this->portal_settings['site_email'], $this->portal_settings['site_name']);
         $fgemail->from([$this->portal_settings['site_email'] => $this->portal_settings['site_name']])->to($admins)->subject(__('Resource Abuse Report'))->emailFormat('both')->send($msg);
         $this->Flash->success('The resource has been reported for abuse.');
         return $this->redirect(['controller' => 'PartnerResources', 'action' => 'navigate', $resource->folder_id]);
     }
     $this->set('resource', $resource);
 }
Ejemplo n.º 15
0
 /**
  * Prepares the `from` email address.
  *
  * @param \Cake\Network\Email\Email $email Email instance
  * @return array
  */
 protected function _prepareFromAddress($email)
 {
     $from = $email->returnPath();
     if (empty($from)) {
         $from = $email->from();
     }
     return $from;
 }
Ejemplo n.º 16
0
 public function esqueci()
 {
     $this->layout = false;
     $mensagem = '';
     if ($this->request->is('post')) {
         $ldap = new LDAP(3);
         $email = $this->request->data['email'];
         if ($ldap->verificaEmail($email)) {
             $token = TableRegistry::get("token");
             $query = $token->find('all', ['conditions' => ['email' => $email . '@smt.ufrj.br']]);
             $number = $query->count();
             if ($number == 0) {
                 $obj = $token->newEntity();
                 $obj->inicio = new \Datetime();
                 $obj->fim = new \DateTime('+ 1 day');
                 $obj->hash = md5($email);
                 $obj->email = $email . '@smt.ufrj.br';
                 $token->save($obj);
                 $html = "<a href='http://intranet.smt.ufrj.br/login/redefinir?token={$obj->hash}'>clique aqui</a>";
                 $send = new Email('gmail');
                 $send->from(['*****@*****.**' => 'Controle de Usuarios'])->emailFormat('html')->to($email . '@smt.ufrj.br')->subject('Instruções para redefinir sua senha')->send('Para redefinir sua senha ' . $html . '.');
                 $mensagem = 6;
             } else {
                 $mensagem = 7;
             }
             return $this->redirect(['controller' => 'login', 'action' => 'index', $mensagem]);
         } else {
             $mensagem = 8;
             return $this->redirect(['controller' => 'login', 'action' => 'index', $mensagem]);
         }
     }
     $this->set(compact('mensagem'));
 }
 public function leadAssigned($lead_id)
 {
     $leads = TableRegistry::get('Leads');
     $partners = TableRegistry::get('Partners');
     $lead = $leads->get($lead_id);
     $partner = $partners->get($lead->partner_id);
     $cmpemail = new Email('default');
     $cmpemail->from([$this->portal_settings['site_email'] => $this->portal_settings['site_name']])->to([$partner->email => $partner->company_name])->subject('Lead "' . $lead->email . '" waiting for acceptance')->emailFormat('html')->template('leadassigned')->viewVars(array('email' => $lead->email, 'vendor_msg' => $partner_lead->note))->send();
     return true;
 }
Ejemplo n.º 18
0
 public function resetpassword($token)
 {
     $this->loadModel('UserPwordResets');
     $upr = $this->UserPwordResets->find('all')->where(['token' => $token, 'status' => 'A', 'expiry_date >' => time()])->first();
     if (isset($upr)) {
         $usrdet = $this->Users->find('all')->where(['username' => $upr->username])->first();
         //print_r($usrdet);exit;
         if (isset($usrdet)) {
             $rchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%^&*()_-=+;:,.?";
             $pwrd = substr(str_shuffle($rchars), 0, 8);
             $usrdet->password = $pwrd;
             $usrdet->role = $usrdet->role;
             if ($this->Users->save($usrdet)) {
                 $site_url = Router::url('/', true);
                 $msg = __('Your password has been changed for the following account:<br>') . $site_url . __(' <br> Username: '******' <br> Password: '******'default');
                 $fgemail->sender($this->portal_settings['site_email'], $this->portal_settings['site_name']);
                 $fgemail->from([$this->portal_settings['site_email'] => $this->portal_settings['site_name']])->to($upr->email)->subject(__('New Password'))->emailFormat('both')->send($msg);
                 $this->Flash->success(__('New log in details have been sent to your email address.'));
                 $upr->status = 'S';
                 $this->UserPwordResets->save($upr);
             }
         }
     } else {
         $this->Flash->error(__('Invalid token'));
     }
     return $this->redirect(['action' => 'login']);
 }
Ejemplo n.º 19
0
 public function desbloqueio()
 {
     $solic = TableRegistry::get("solicitacao");
     $dados = $this->request->data;
     $temSolicitacao = $solic->find('all', ['conditions' => ['idUsuario' => $this->request->data['idUsuario'], 'tipoSolicitacao' => 3, 'executado' => false]])->count() > 0;
     if (!$temSolicitacao) {
         $solicitacao = $solic->newEntity();
         $solicitacao->tipoSolicitacao = 3;
         $solicitacao->idUsuario = $this->request->data['idUsuario'];
         $solicitacao->solicitante = $this->request->session()->read('usuario')->idUsuario;
         $solicitacao->justificativa = $this->request->data['justificativa'];
         $this->Flash->success(__('Solicitação Enviada.'));
         $solic->save($solicitacao);
         $sus = $this->Usuario->find()->where(['Usuario.idTipoUsuario' => 1]);
         $emails = array();
         foreach ($sus as $su) {
             array_push($emails, $su->login . '@smt.ufrj.br');
         }
         $email = new Email('gmail');
         $email->from(['*****@*****.**' => 'Sistema Intranet SMT'])->to($emails)->subject('Pedido de bloqueio')->send('Novo Pedido de desbloqueio aguardando aprovação');
         return $this->redirect(['action' => 'index']);
     } else {
         $this->Flash->error(__('Usuario já tem essa solicitação pendente.'));
         return $this->redirect(['action' => 'index']);
     }
     $this->set(compact('solicitacao', 'temSolicitacao', dados));
 }
Ejemplo n.º 20
0
 /**
  * Add a new order method
  *
  * This is to let customers(users) start a new order and will probably be automated by the shopping cart
  * in all cases unless an admin user is generating an order manually.
  *
  * @return void Redirects on successful add, renders view otherwise.
  */
 public function add()
 {
     //create a new order entity in the database
     $order = $this->Orders->newEntity();
     //if the http request is of type post then
     if ($this->request->is('post')) {
         //use the data in the add order form to update the new order Database entry
         $order = $this->Orders->patchEntity($order, $this->request->data);
         //pre set the ordered_date and courier id as we are not including that this build.
         $order->ordered_date = date("Y-m-d");
         $order->courier_id = "1";
         //set gged in user id as the order user id property
         $loggedUser = $this->request->session()->read('user');
         $order->user_id = $loggedUser['id'];
         if ($this->request->session()->read('userRole') == 'user') {
             //grab the users customer ID to add to the order
             $query = TableRegistry::get('Customers')->find();
             $query->where(['user_id' => $order->user_id]);
             foreach ($query as $orderCustomer) {
                 //set the ordering customer id as users ID
                 $order->customer_id = $orderCustomer['id'];
             }
         }
         //otherwise we show the drop down list and select the customer ID from there, allowing for
         //  customer selection on order creation for,
         //if the order save process is a success
         if ($this->Orders->save($order)) {
             //show user it worked and redirect them back to the order listing (will soon be only their orders listed)
             $this->Flash->success('The order has been placed in our system. Your order will be processed soon.');
             //send an email to rick letting him know that an order was placed.
             //Send email to customer with their new reset password hashed link/url
             //create email object and set email config settings
             $orderEmail = new Email('default');
             $orderEmail->transport('default');
             //set the type of email format and use our custom template.
             $orderEmail->emailFormat('html');
             $orderEmail->template('order_email');
             //set the email to send to
             $orderEmail->to(Configure::read('orderRecievedEmail'));
             $orderEmail->subject('Solemate Order has been placed on ' . date("Y-m-d"));
             //Set the email headers.
             $orderEmail->from(['*****@*****.**' => 'Solemate Doormats Web Orders']);
             $orderEmail->sender(['*****@*****.**' => 'Solemate Doormats inc']);
             $orderEmail->replyTo('*****@*****.**');
             //email message and send line
             $orderEmail->send('Hi there admin this is an automated email to let you know a new order has been placed on the website ordering system, the order id is ' . $order->id . '. The customer id was ' . $order->customer_id);
             return $this->redirect(['action' => 'index']);
         } else {
             $this->Flash->error('The order could not be saved. Please, try again.');
         }
     }
     //get all couriers and customers ready for linking to this new order
     //(customer = orderie & courier = delivery choice by customer/user)
     $couriers = $this->Orders->Couriers->find('list', ['limit' => 200]);
     //check if the user is a salesRep then just show only his customers.
     if ($this->request->session()->read('userRole') == 'salesRep') {
         //grab all customers from the model
         //$allCusts = $this->Customers->find("all");
         $query = TableRegistry::get('Customers')->find("all");
         //create space for just the logged in users customers
         $repCustomers = array();
         //loop through all customers
         foreach ($query as $aCust) {
             //if the logged in user id matches the stored customer-user id
             if ($this->Auth->user('id') == $aCust['user_id']) {
                 //debug($aCust);
                 //push the specific contents onto the customers array for display on add order view page.
                 array_push($repCustomers, array($aCust['id'] => $aCust['first_name'] . ' ' . $aCust['last_name']));
             }
         }
         //now set the view variable as the users customers only.
         $customers = $repCustomers;
     } else {
         if ($this->request->session()->read('userRole') == 'admin') {
             $customers = $this->Orders->Customers->find('list', ['limit' => 200]);
         }
     }
     //set the ViewVars for the view page add.
     $this->set(compact('order', 'couriers', 'customers'));
     $this->set('_serialize', ['order']);
 }
Ejemplo n.º 21
0
 /**
  * Reset Password method
  *
  * @param string|null $id User id.
  * @return void Redirects to password reset page.
  * @throws \Cake\Network\Exception\NotFoundException When user record not found.
  *
  * @description This will run when the user clicks on the reset password
  *  link to generate a new replacment password. This is done by entering their email address
  *    that they registered with, this ensures the user owns the account 
  *   they are resetting the password on and also that they cant intercept the
  *   new password.  We firstly generate a random string storing it in the database then
  * this string is sent as part of the users link to click on again ensuring the user requesting
  * the new password is the one who owns the account.  After the user arrives at the url they are
  *  presented with a small form consisting of 2 password fields: Password & Confirm Password
  * after a quick check that the passwords match the new password is Hashed and stored in the DB
  *  and the user is returned to the log in page with a flash message telling them it worked 
  * if there was an error the page will not re direct and will display the error allowing user to retry.
  *
  */
 public function resetPassword()
 {
     //set this function to only run with data from a post request
     //$this->request->allowMethod(['post']);
     //check the form has been submitted
     if (isset($_POST['txtEmail'])) {
         /*
             Build a custom SQL query object to find all users and 
             filter that to the user whos email matches the form data
             on the reset password form.
         */
         $query = TableRegistry::get('Users')->find();
         $query->where(['email' => $_POST['txtEmail']]);
         //loop through query result
         foreach ($query as $user) {
             //when we match on the right user data from our DB lookup
             if ($user->email == $_POST['txtEmail']) {
                 //set the viewVariable to this userEmail.
                 $selectedUser = $user;
             }
         }
         //end foreach query result (should only be one in this case)
         if (isset($selectedUser)) {
             //if the selectedUser data isSet then set the viewVar with this data else do nothing to prevent empty form submit.
             $this->set('selectedUser', $selectedUser);
             //Create new random HASHED String to send to user
             // for security and randomness i mixed older md5 with nice sha256 ;)
             $intermediateSalt = md5(uniqid(rand(), true));
             //set a temp string of 7 digits in length no decimal places
             $salt = substr($intermediateSalt, 0, 7);
             //now run random string through a 256bit sha encrypt  - maybe overkill?
             $randPassword = hash("sha256", $salt);
             //update the selectedUsers reset value from old to new.
             $selectedUser->reset = $randPassword;
             //Store temp HASH in user database
             //store the id of the user in question to save time on a db lookup.
             $id = $selectedUser->id;
             //Send email to customer with their new reset password hashed link/url
             //create email object and set email config settings
             $tempEmail = new Email('default');
             $tempEmail->transport('default');
             //set the type of email format and use our custom template.
             $tempEmail->emailFormat('html');
             $tempEmail->template('sendPwreset');
             //set the email to send to
             $tempEmail->to($selectedUser->email);
             $tempEmail->subject('Solemate Password Reset');
             //Set the email headers.
             $tempEmail->from(['*****@*****.**' => 'Solemate Doormats inc']);
             $tempEmail->sender(['*****@*****.**' => 'Solemate Doormats inc']);
             $tempEmail->replyTo('*****@*****.**');
             //generate a url using our generated random hash and user id
             $fullUrl = Router::url(array('controller' => 'Users', 'action' => 'resetPassword', 'pwr' => $selectedUser->reset, 'id' => $selectedUser->id), true);
             //Build the message to send to the users requesting the new password.
             $message = "Solemate Doormats Password Reset<br />We received a requested to reset the password on your account, If you made a mistake by clicking the forgot password link then please feel free to disregard this email.  ";
             $message .= " We would like you to click the link below to reset your login password,<br />";
             $message .= "<a href='" . $fullUrl . "'>Click here to reset/change your password.</a><br />";
             $message .= "If you continue to get these password reset emails without requesting them feel free to contact the admin staff by email here at Solemate Doormats and we can investigate it for you.";
             $message .= ".  Here at Solemate Doormats we keep our users passwords private even from the admins.  Feel free to drop us a email if";
             $message .= " you would like more information on your account security, or if you feel someone else is requesting these password resets maliciously.";
             $message .= "<br /><br /><br /><b>Privacy Agreement:</b><i>All content sent / displayed from Solemate Doormats / IB Australia is for private customer use only, any materials shown in these emails are copyright";
             $message .= " protected by Solemate Doormats and should under no circumstance be used without written consent from the company owner, any use of these materials";
             $message .= " without consent will be seen as an act of IP copyright breach and will be followed with appropriate legal action.  If you are not the intended recipient of this email please disregard and delete this message, if this is in hard copy please shred any copies you may have received in error.  ";
             $message .= "Materials covered by I.P. copyright: Logo's, Doormat print's / design's, the Solemate Doormats trading name, Solemate Doormats colour scheme's.";
             $message .= "<br /><p align='center'> &copy; 2015 IB Australia - Solemate Doormats</p></i>";
             /*
               Use a custom query to save our new random string into the users db entry for checking 
               user email starts the password reset.
             */
             $query2 = TableRegistry::get('Users')->find();
             $query2->update('Users')->set(['reset' => $randPassword])->where(['id' => $id]);
             $stmt = $query2->execute();
             //May not be needed
             $tempEmail->viewVars(array('cust' => $selectedUser));
             //email message and send line
             $tempEmail->send($message);
         } else {
             $this->Flash->error('Error: This user email address was not found in our database.  Try again with the address you registered with please.');
         }
     } else {
         if (isset($_GET['pwr']) && isset($_GET['id'])) {
             //set the user ID from get ID passed then lookup all users by that ID number.
             $id = $_GET['id'];
             $user = $this->Users->get($id, ['contain' => []]);
             //if the request is of type post, patch or put then
             if ($this->request->is(['patch', 'post', 'put'])) {
                 //set the new data to the current user in the user variable.
                 $user = $this->Users->patchEntity($user, $this->request->data);
                 //if the save of the user data(password) is successfull then
                 if ($this->Users->save($user)) {
                     $this->Flash->success('Success: Your login password has been changed ' . $user->username . '. ');
                     return $this->redirect(['action' => 'login']);
                 } else {
                     $this->Flash->error('The new password could not be saved. Please, try again.');
                 }
             }
             //end of if request is patch,post,put
             //set the current user data as a viewVariable.
             $this->set(compact('user'));
             $this->set('_serialize', ['user']);
         }
     }
     //end of else if GET variables are set
 }
 /**
  * Demande de rappel d'un mot de passe oublié par l'utilisateur
  * Génère un ticket temporaire de changement de mot de passe
  * => Accès par vue User::login()
  * 
  * @return void
  */
 public function reinitialiserMotPasse()
 {
     $content_title = "Réinitialisation de mot de passe";
     $this->layout = "login";
     if ($this->request->is(['post'])) {
         $data = $this->request->data;
         $userEntity = $this->Users->find('all')->where(['email' => $data['email'], 'actif' => true])->first();
         if (!empty($userEntity)) {
             $user = $userEntity->toArray();
             // Génération d'une clé
             $code = sha1($user['email'] . rand(0, 100));
             $link = Router::url(['controller' => 'Users', 'action' => 'nouveauMotPasse', $code], true);
             // Sauvegarde des nouvelles données de réinit de pass
             $userEntity->change_pass_code = $code;
             $userEntity->change_pass_date = date('Y-m-d H:i:s');
             $this->Users->save($userEntity);
             $email = new Email('default');
             try {
                 $email->from([EMAIL_PAS_RESPONDRE => APP_NAME])->to([$user['email'] => $user['prenom']])->subject("Reinitialisation du mot de passe")->emailFormat("html")->template('reinitialiser_mot_pass', 'default')->viewVars(['link' => $link, 'title_for_layout' => "Lien de réinitialisation"])->send('My message');
                 $this->Flash->success("Un email a été envoyé à votre adresse de messagerie contenant les instructions pour la réinitialisation de votre mot de passe.");
             } catch (Exception $ex) {
                 echo 'Exception : ', $ex->getMessage(), "\n";
             }
             return $this->redirect($this->referer());
         } else {
             $this->Flash->error("L'adresse e-mail ne existe pas, ou ce compte a été désactivé. Contactez un administrateur pour plus de précision.");
         }
     }
     $this->set(compact('content_title'));
 }
Ejemplo n.º 23
0
 public function teste()
 {
     $email = new Email('gmail');
     $email->from(['*****@*****.**' => 'Controle de Usuarios'])->emailFormat('html')->to('*****@*****.**')->subject('Notificação de Usuarios a expirar')->send('Cron sucedido');
 }
Ejemplo n.º 24
0
 /**
  * _sendEmail() method
  * 
  * Reusable function for sending user emails
  * 
  * @return void
  */
 private function _sendEmail(JobFunc $jobfunc, User $user)
 {
     $this->log('Send verify email to ' . 'id: ' . $user->id . ' ' . 'username: '******' ' . 'email: ' . $user->email . ' ' . 'func_data: ' . $jobfunc->func_data, 'info');
     if (Configure::read('debug') && Configure::read('sendEmail')) {
         // Wrap sending email in try/catch
         $email = new Email('default');
         $email->template('verify')->emailFormat('html')->viewVars(['emailAddr' => $user->email, 'verifyHash' => $jobfunc->func_data]);
         $email->from(['*****@*****.**' => 'FindMyPet.com'])->to('*****@*****.**')->subject('About')->send('Confirm Registration');
     }
 }
Ejemplo n.º 25
0
 /**
  * testGetLastResponse method
  *
  * @return void
  */
 public function testGetLastResponse()
 {
     $this->assertEmpty($this->SmtpTransport->getLastResponse());
     $this->socket->expects($this->any())->method('connect')->will($this->returnValue(true));
     $this->socket->expects($this->at(0))->method('read')->will($this->returnValue(false));
     $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n"));
     $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n");
     $this->socket->expects($this->at(3))->method('read')->will($this->returnValue(false));
     $this->socket->expects($this->at(4))->method('read')->will($this->returnValue("250-PIPELINING\r\n"));
     $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250-SIZE 102400000\r\n"));
     $this->socket->expects($this->at(6))->method('read')->will($this->returnValue("250-VRFY\r\n"));
     $this->socket->expects($this->at(7))->method('read')->will($this->returnValue("250-ETRN\r\n"));
     $this->socket->expects($this->at(8))->method('read')->will($this->returnValue("250-STARTTLS\r\n"));
     $this->socket->expects($this->at(9))->method('read')->will($this->returnValue("250-AUTH PLAIN LOGIN\r\n"));
     $this->socket->expects($this->at(10))->method('read')->will($this->returnValue("250-AUTH=PLAIN LOGIN\r\n"));
     $this->socket->expects($this->at(11))->method('read')->will($this->returnValue("250-ENHANCEDSTATUSCODES\r\n"));
     $this->socket->expects($this->at(12))->method('read')->will($this->returnValue("250-8BITMIME\r\n"));
     $this->socket->expects($this->at(13))->method('read')->will($this->returnValue("250 DSN\r\n"));
     $this->SmtpTransport->connect();
     $expected = array(array('code' => '250', 'message' => 'PIPELINING'), array('code' => '250', 'message' => 'SIZE 102400000'), array('code' => '250', 'message' => 'VRFY'), array('code' => '250', 'message' => 'ETRN'), array('code' => '250', 'message' => 'STARTTLS'), array('code' => '250', 'message' => 'AUTH PLAIN LOGIN'), array('code' => '250', 'message' => 'AUTH=PLAIN LOGIN'), array('code' => '250', 'message' => 'ENHANCEDSTATUSCODES'), array('code' => '250', 'message' => '8BITMIME'), array('code' => '250', 'message' => 'DSN'));
     $result = $this->SmtpTransport->getLastResponse();
     $this->assertEquals($expected, $result);
     $email = new Email();
     $email->from('*****@*****.**', 'CakePHP Test');
     $email->to('*****@*****.**', 'CakePHP');
     $this->socket->expects($this->at(0))->method('write')->with("MAIL FROM:<*****@*****.**>\r\n");
     $this->socket->expects($this->at(1))->method('read')->will($this->returnValue(false));
     $this->socket->expects($this->at(2))->method('read')->will($this->returnValue("250 OK\r\n"));
     $this->socket->expects($this->at(3))->method('write')->with("RCPT TO:<*****@*****.**>\r\n");
     $this->socket->expects($this->at(4))->method('read')->will($this->returnValue(false));
     $this->socket->expects($this->at(5))->method('read')->will($this->returnValue("250 OK\r\n"));
     $this->SmtpTransport->setEmail($email);
     $this->SmtpTransport->sendRcpt();
     $expected = array(array('code' => '250', 'message' => 'OK'));
     $result = $this->SmtpTransport->getLastResponse();
     $this->assertEquals($expected, $result);
 }
Ejemplo n.º 26
0
 /**
  * sendVerificationEmail method
  *
  * @param User $user the User info.
  * @return bool
  */
 public function sendVerificationEmail($user, $url = null)
 {
     $email = new Email(Configure::read('auth_plugin.email_settings.transport'));
     $code = $user->emailcheckcode;
     $verificationUrl = Configure::read('debug') ? Configure::read('auth_plugin.verify_url.dev') : Configure::read('auth_plugin.verify_url.production');
     $email->from(Configure::read('auth_plugin.email_settings.from'))->emailFormat('html')->template('register', 'default')->viewVars(['name' => $user->personalinformation->first_name, 'serviceName' => Configure::read('auth_plugin.service_name'), 'code' => $code, 'url' => $verificationUrl, 'wcBaseUrl' => Configure::read('wc_base_url')])->to($user->email)->subject(Configure::read('auth_plugin.email_settings.register_subject'));
     return $email->send();
 }
Ejemplo n.º 27
0
 /**
  * @param mixed $charset
  * @param mixed $headerCharset
  * @return CakeEmail
  */
 protected function _getEmailByNewStyleCharset($charset, $headerCharset)
 {
     $email = new Email(array('transport' => 'debug'));
     if (!empty($charset)) {
         $email->charset($charset);
     }
     if (!empty($headerCharset)) {
         $email->headerCharset($headerCharset);
     }
     $email->from('*****@*****.**', 'どこかの誰か');
     $email->to('*****@*****.**', 'どこかのどなたか');
     $email->cc('*****@*****.**', 'ミク');
     $email->subject('テストメール');
     $email->send('テストメールの本文');
     return $email;
 }
Ejemplo n.º 28
0
 public function aprovacaoSU()
 {
     $usuario = TableRegistry::get("usuario");
     $id = $this->request->data['idSolicitacao'];
     $alteracao = '';
     $solicitacao = $this->Solicitacao->get($id, ['contain' => []]);
     $user = $usuario->get($solicitacao->idUsuario);
     $user->login = $this->request->data['login'];
     $user->data_exp = new \DateTime();
     $user->ativo = false;
     $user->senha = 'q1w2e3r4';
     if ($usuario->save($user)) {
         //$this->Flash->success(__('Usuario Aprovado.'));
         $brisa = new Google();
         $brisa->chamaGoogle()->adicionaUsuario($user->get('nomeUsuario'), $user->get('login'), 'q1w2e3r4');
         $ldap = new LDAP(3);
         $obj = $ldap->monta_objeto($user, true);
         $retorno = $ldap->addUser($user->login, $obj);
         $solicitacao->executor = $this->request->session()->read('usuario')->idUsuario;
         $solicitacao->executado = true;
         $this->Solicitacao->save($solicitacao);
         $professor = $this->Solicitacao->newEntity();
         $professor->solicitante = $user->idUsuario;
         $professor->idUsuario = $user->idUsuario;
         $professor->tipoSolicitacao = 8;
         $professor->justificativa = 'Aprovação Aluno no Projeto';
         $professor->professor = $user->profResponsavel;
         $this->Solicitacao->save($professor);
         $email = new Email('gmail');
         $email->from(['*****@*****.**' => 'Sistema Intranet SMT'])->to($usuario->get($professor->professor)->login . '@smt.ufrj.br')->subject('Aguardando Aprovação')->send('Novo Aluno vinculado a seu projeto');
         $email = new Email('gmail');
         $email->from(['*****@*****.**' => 'Sistema Intranet SMT'])->emailFormat('html')->to($user->email)->subject('Dados de Acesso ao sistema')->send("<p>Seu cadastro foi aprovado pelo Administrador. Segue os dados de acesso: </p><p>Sistema</p>\n\t\t\t\t<table><tr><th>Usuario</th><th>Senha</th></tr><tr><td>{$user->login}</td><td>q1w2e3r4</td></table>\n\t\t\t\t<p>Email SMT</p><table><tr><th>Email</th><th>Senha</th></tr><tr><td>{$user->login}@smt.ufrj.br</td><td>q1w2e3r4</td></table>\n\t\t\t\t<p>Favor mudar a senha no primeiro acesso</p>");
         $texto = '<p>- O usuário terá acesso a diferentes sistemas operacionais através do mesmo username (login) e a diversos equipamentos computacionais e eletrônicos. As contas são individuais e de inteira responsabilidade do usuário. É proibido empréstimo do acesso à conta do usuário, wi-fi e códigos do porteiro eletrônico a terceiros. Qualquer dano causado à rede e equipamentos SMT ou a outras redes a partir de uma conta da rede SMT será de inteira responsabilidade do proprietário da conta. </p>';
         $texto .= '<p>- Os laboratórios são de uso exclusivo dos alunos, funcionários e professores do SMT ou profissionais envolvidos em projetos coordenados pelo Laboratório.</p>';
         $texto .= '<p>- Não é permitido: </p>';
         $texto .= '<p>a) O uso de jogos e similares;</p>';
         $texto .= '<p>b) O acesso a páginas com conteúdo pornográfico;</p>';
         $texto .= '<p>c) Fumar no interior do Laboratório;</p>';
         $texto .= '<p>d) A instalação de programas, bem como, a alteração da configuração dos computadores sem a autorização de algum membro da administração da rede SMT;</p>';
         $texto .= '<p>- Cada usuário possui um espaço limitado para armazenar dados e e-mails no domínio SMT. Ao ultrapassar o limite definido o usuário não conseguirá enviar ou receber novos e-mails, adicionar novos documentos ao drive e poderá ter problemas gerais com sua conta. Os limites para armazenamento de dados e e-mails serão de 15GB.</p>';
         $texto .= '<p>- Apesar de existir um sistema de Backup, a administração da rede do SMT não pode garantir a integridade dos dados armazenados no servidor, isto é, não pode realizar cópias de segurança dos dados. Cada usuário deve manter suas cópias de segurança por conta própria em meios removíveis (HDs, CDs, etc).</p>';
         $texto .= '<p>- Dicas de utilização dos recursos da rede SMT (impressoras, envio / recepção de mensagens eletrônicas, etc) podem ser encontradas na Home Page do Laboratório. (http://www.smt.ufrj.br) </p>';
         $texto .= '<p>- Para acessar o seu e-mail, utilize a página de logon do SMT no endereço https://mail.google.com. </p>';
         $texto .= '<p>- Dúvidas, críticas e sugestões devem ser enviadas para o endereço netnetadmin@smt.ufrj.br .</p>';
         $email = new Email('gmail');
         $email->from(['*****@*****.**' => 'Sistema Intranet SMT'])->emailFormat('html')->to($user->email)->subject('Termo de Utilização do Sistema')->send($texto);
         $auditoriaTable = TableRegistry::get("Auditoria");
         $auditoria = $auditoriaTable->newEntity();
         $auditoria->idObjeto = $solicitacao->idUsuario;
         $auditoria->objeto = 'Solicitação';
         $auditoria->acao = 'Aprovação de Aluno pelo SU';
         //$auditoria->dataAcao = (new \DateTime())->format('Y-m-d H:i:s');
         $auditoria->idUsuario = $session = $this->request->session()->read('usuario')->idUsuario;
         $auditoriaTable->save($auditoria);
     }
     $this->Flash->success(__('Usuário Aprovado.'));
     $this->set(compact('user', 'obj', 'data', 'ano', 'dataPronta'));
     return $this->redirect(['action' => 'index']);
 }
Ejemplo n.º 29
0
 /**
  * Sends reset email
  *
  * @param entity $user User entity.
  * 
  * @return void
  */
 public function sendResetEmail($user)
 {
     $reset_key = uniqid();
     $user->{Configure::read('Lil.passwordResetField')} = $reset_key;
     if ($this->save($user)) {
         $email = new Email('default');
         $email->from([Configure::read('Lil.from.email') => Configure::read('Lil.from.name')]);
         $email->to($user->{Configure::read('Lil.userEmailField')});
         $email->subject(__d('lil', 'Password Reset'));
         $email->template('Lil.reset');
         $email->emailFormat('text');
         $email->viewVars(['reset_key' => $reset_key]);
         $email->helpers(['Html']);
         return $email->send();
     }
     return false;
 }
Ejemplo n.º 30
0
 public function sendremind()
 {
     $this->loadModel('Shows');
     $this->loadModel('Users');
     $this->loadModel('ShowUserPerms');
     $showsToRemind = $this->Shows->find('list', ['valueField' => 'name', 'keyField' => 'id'])->where(['Shows.is_active' => 1])->where(['Shows.is_reminded' => 1]);
     if (sizeof($showsToRemind->toArray()) > 0) {
         $usersToRemindArr = $this->ShowUserPerms->find('list', ['valueField' => 'id', 'keyField' => 'user_id'])->where(['show_id IN' => array_keys($showsToRemind->toArray())])->where(['is_paid' => 1]);
         $usersToRemind = $this->Users->find()->where(['is_active' => 1])->where(['is_notified' => 1])->where(['id IN' => array_keys($usersToRemindArr->toArray())]);
         foreach ($usersToRemind as $thisUser) {
             $this->out('Sending to: ' . $thisUser->first);
             $email = new Email();
             $email->transport('default');
             $email->emailFormat('both');
             $email->to($thisUser->username);
             $email->subject('Hours are Due!');
             $email->from('*****@*****.**');
             $email->template('hourremind');
             $email->viewVars(['name' => $thisUser->first . " " . $thisUser->last]);
             $email->send();
         }
     }
     $this->verbose('  E-Mail(s) Sent.');
 }