/**
  * Sends out email via Mandrill
  *
  * @param CakeEmail $email
  * @return array
  */
 public function send(CakeEmail $email)
 {
     // CakeEmail
     $this->_cakeEmail = $email;
     $from = $this->_cakeEmail->from();
     list($fromEmail) = array_keys($from);
     $fromName = $from[$fromEmail];
     $this->_config = $this->_cakeEmail->config();
     $this->_headers = $this->_cakeEmail->getHeaders();
     $message = array('html' => $this->_cakeEmail->message('html'), 'text' => $this->_cakeEmail->message('text'), 'subject' => mb_decode_mimeheader($this->_cakeEmail->subject()), 'from_email' => $fromEmail, 'from_name' => $fromName, 'to' => array(), 'headers' => array('Reply-To' => $fromEmail), 'important' => false, 'track_opens' => null, 'track_clicks' => null, 'auto_text' => null, 'auto_html' => null, 'inline_css' => null, 'url_strip_qs' => null, 'preserve_recipients' => null, 'view_content_link' => null, 'tracking_domain' => null, 'signing_domain' => null, 'return_path_domain' => null, 'merge' => true, 'tags' => null, 'subaccount' => null);
     $message = array_merge($message, $this->_headers);
     foreach ($this->_cakeEmail->to() as $email => $name) {
         $message['to'][] = array('email' => $email, 'name' => $name, 'type' => 'to');
     }
     foreach ($this->_cakeEmail->cc() as $email => $name) {
         $message['to'][] = array('email' => $email, 'name' => $name, 'type' => 'cc');
     }
     foreach ($this->_cakeEmail->bcc() as $email => $name) {
         $message['to'][] = array('email' => $email, 'name' => $name, 'type' => 'bcc');
     }
     $attachments = $this->_cakeEmail->attachments();
     if (!empty($attachments)) {
         $message['attachments'] = array();
         foreach ($attachments as $file => $data) {
             $message['attachments'][] = array('type' => $data['mimetype'], 'name' => $file, 'content' => base64_encode(file_get_contents($data['file'])));
         }
     }
     $params = array('message' => $message, "async" => false, "ip_pool" => null, "send_at" => null);
     return $this->_exec($params);
 }
 private function _sendPart()
 {
     if (empty($this->_recipients)) {
         return true;
     }
     $json = array('to' => $this->_getAddress(array_splice($this->_recipients, 0, $this->_config['count'])), 'category' => !empty($this->_headers['X-Category']) ? $this->_headers['X-Category'] : $this->_config['category']);
     //Sendgrid Substitution Tags
     if (!empty($this->_headers['X-Sub'])) {
         foreach ($this->_headers['X-Sub'] as $key => $value) {
             $json['sub'][$key] = array_splice($value, 0, $this->_config['count']);
         }
     }
     $params = array('api_user' => $this->_config['username'], 'api_key' => $this->_config['password'], 'x-smtpapi' => json_encode($json), 'to' => '*****@*****.**', 'subject' => $this->_cakeEmail->subject(), 'html' => $this->_cakeEmail->message('html'), 'text' => $this->_cakeEmail->message('text'), 'from' => $this->_config['from'], 'fromname' => $this->_config['fromName'], 'replyto' => array_keys($this->_replyTo)[0]);
     $attachments = $this->_cakeEmail->attachments();
     if (!empty($attachments)) {
         foreach ($attachments as $key => $value) {
             $params['files[' . $key . ']'] = '@' . $value['file'];
         }
     }
     $result = json_decode($this->_exec($params));
     if ($result->message != 'success') {
         return $result;
     } else {
         return $this->_sendPart();
     }
 }
 /**
  * Sends out email via SparkPost
  *
  * @param CakeEmail $email
  * @return array
  */
 public function send(CakeEmail $email)
 {
     // CakeEmail
     $this->_cakeEmail = $email;
     $this->_config = $this->_cakeEmail->config();
     $this->_headers = $this->_cakeEmail->getHeaders();
     // Not allowed by SparkPost
     unset($this->_headers['Content-Type']);
     unset($this->_headers['Content-Transfer-Encoding']);
     unset($this->_headers['MIME-Version']);
     unset($this->_headers['X-Mailer']);
     $from = $this->_cakeEmail->from();
     list($fromEmail) = array_keys($from);
     $fromName = $from[$fromEmail];
     $message = ['html' => $this->_cakeEmail->message('html'), 'text' => $this->_cakeEmail->message('text'), 'from' => ['name' => $fromName, 'email' => $fromEmail], 'subject' => mb_decode_mimeheader($this->_cakeEmail->subject()), 'recipients' => [], 'transactional' => true];
     foreach ($this->_cakeEmail->to() as $email => $name) {
         $message['recipients'][] = ['address' => ['email' => $email, 'name' => $name], 'tags' => $this->_headers['tags']];
     }
     foreach ($this->_cakeEmail->cc() as $email => $name) {
         $message['recipients'][] = ['address' => ['email' => $email, 'name' => $name], 'tags' => $this->_headers['tags']];
     }
     foreach ($this->_cakeEmail->bcc() as $email => $name) {
         $message['recipients'][] = ['address' => ['email' => $email, 'name' => $name], 'tags' => $this->_headers['tags']];
     }
     unset($this->_headers['tags']);
     $attachments = $this->_cakeEmail->attachments();
     if (!empty($attachments)) {
         $message['attachments'] = array();
         foreach ($attachments as $file => $data) {
             if (!empty($data['contentId'])) {
                 $message['inlineImages'][] = array('type' => $data['mimetype'], 'name' => $data['contentId'], 'data' => base64_encode(file_get_contents($data['file'])));
             } else {
                 $message['attachments'][] = array('type' => $data['mimetype'], 'name' => $file, 'data' => base64_encode(file_get_contents($data['file'])));
             }
         }
     }
     $message = array_merge($message, $this->_headers);
     // Load SparkPost configuration settings
     $config = ['key' => $this->_config['sparkpost']['api_key']];
     if (isset($this->_config['sparkpost']['timeout'])) {
         $config['timeout'] = $this->_config['sparkpost']['timeout'];
     }
     // Set up HTTP request adapter
     $httpAdapter = new Ivory\HttpAdapter\Guzzle6HttpAdapter($this->__getClient());
     // Create SparkPost API accessor
     $sparkpost = new SparkPost\SparkPost($httpAdapter, $config);
     // Send message
     try {
         return $sparkpost->transmission->send($message);
     } catch (SparkPost\APIResponseException $e) {
         // TODO: Determine if BRE is the best exception type
         throw new BadRequestException(sprintf('SparkPost API error %d (%d): %s (%s)', $e->getAPICode(), $e->getCode(), ucfirst($e->getAPIMessage()), $e->getAPIDescription()));
     }
 }
Beispiel #4
0
 public function _sendMails($to, $sub = '', $contents = '', $attachments = null, $cc = null, $bcc = null)
 {
     //prd($contents);
     if (empty($from)) {
         $from = strtolower(Configure::read('Site.email'));
     }
     $Email = new CakeEmail();
     $Email->config('smtp');
     $Email->emailFormat('html');
     $Email->subject($sub);
     $Email->template('default', 'default');
     $Email->to($to);
     $Email->from(array($from => $sub));
     $Email->replyTo('*****@*****.**', "Meocart Team");
     if (!empty($cc)) {
         $Email->cc($cc);
     }
     if (!empty($bcc)) {
         $Email->bcc($bcc);
     }
     if (!empty($attachments) && $attachments != '' && is_array($attachments)) {
         $Email->attachments($attachments);
     }
     $Email->viewVars(array('content' => $contents));
     try {
         if ($Email->send()) {
             return true;
         }
         return false;
     } catch (Exception $e) {
         return $e->getMessage();
     }
 }
 public function contact()
 {
     $this->loadModel('Contact');
     if ($this->request->is('post')) {
         $this->Contact->set($this->request->data);
         if ($this->Contact->validates()) {
             App::uses('CakeEmail', 'Network/Email');
             if ($this->request->data['Contact']['subject'] == '') {
                 $this->request->data['Contact']['subject'] = 'Contact';
             }
             $Email = new CakeEmail('smtp');
             $Email->viewVars(array('mailData' => $this->request->data));
             $Email->template('contact', 'default');
             $Email->emailFormat('html');
             $Email->from(array($this->request->data['Contact']['mail'] => $this->request->data['Contact']['name']));
             $Email->to('*****@*****.**');
             $Email->subject($this->request->data['Contact']['subject']);
             $Email->attachments(array('logo.png' => array('file' => WWW_ROOT . '/img/icons/logo.png', 'mimetype' => 'image/png', 'contentId' => 'logo')));
             $Email->send();
             $this->Flash->success(__('Votre mail a bien été envoyé.'));
             return $this->redirect($this->referer());
         } else {
             $this->Session->write('errors.Contact', $this->Contact->validationErrors);
             $this->Session->write('data', $this->request->data);
             $this->Session->write('flash', 'Le mail n’a pas pu être envoyé. Veuillez réessayer SVP.');
             return $this->redirect($this->referer());
         }
     }
 }
 /**
  * Send email via Mailgun
  *
  * @param CakeEmail $email
  * @return array
  * @throws Exception
  */
 public function send(CakeEmail $email)
 {
     if (Configure::read('Mailgun.preventManyToRecipients') !== false && count($email->to()) > 1) {
         throw new Exception('More than one "to" recipient not allowed (set Mailgun.preventManyToRecipients = false to disable check)');
     }
     $mgClient = new Mailgun($this->_config['mg_api_key']);
     $headersList = array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject');
     $params = [];
     foreach ($email->getHeaders($headersList) as $header => $value) {
         if (isset($this->_paramMapping[$header]) && !empty($value)) {
             $key = $this->_paramMapping[$header];
             $params[$key] = $value;
         }
     }
     $params['text'] = $email->message(CakeEmail::MESSAGE_TEXT);
     $params['html'] = $email->message(CakeEmail::MESSAGE_HTML);
     $attachments = array();
     foreach ($email->attachments() as $name => $info) {
         $attachments['attachment'][] = '@' . $info['file'];
     }
     try {
         $result = $mgClient->sendMessage($this->_config['mg_domain'], $params, $attachments);
         if ($result->http_response_code != 200) {
             throw new Exception($result->http_response_body->message);
         }
     } catch (Exception $e) {
         throw $e;
     }
     return $result;
 }
 /**
  * Send
  *
  * @param CakeEmail $email objeto mail
  * @return array
  * @throws SocketException
  */
 public function send(CakeEmail $email)
 {
     $post = array();
     $postPreprocess = array_merge($email->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject')), array('text' => $email->message(CakeEmail::MESSAGE_TEXT), 'html' => $email->message(CakeEmail::MESSAGE_HTML)));
     foreach ($postPreprocess as $k => $v) {
         if (!empty($v)) {
             $post[strtolower($k)] = $v;
         }
     }
     if ($attachments = $email->attachments()) {
         $i = 1;
         foreach ($attachments as $attachment) {
             $post['attachment[' . $i . ']'] = "@" . $attachment["file"];
             $i++;
         }
     }
     $ch = curl_init('https://api.mailgun.net/v2/' . $this->_config['mailgun_domain'] . '/messages');
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_USERPWD, 'api:' . $this->_config['api_key']);
     curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
     $response = curl_exec($ch);
     if ($response === false) {
         throw new SocketException("Curl had an error.  Message: " . curl_error($ch), 500);
     }
     $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     if ($httpStatus != 200) {
         throw new SocketException("Mailgun request failed.  Status: {$httpStatus}, Response: {$response}", 500);
     }
     curl_close($ch);
     return array('headers' => $this->_headersToString($email->getHeaders(), PHP_EOL), 'message' => implode(PHP_EOL, $email->message()));
 }
 protected function addAttachments(CakeEmail $email)
 {
     $attachments = $email->attachments();
     $this->data['attachments'] = array();
     foreach ($attachments as $filename => $data) {
         $this->data['attachments'][] = array('filename' => $filename, 'content' => file_get_contents($data['file']));
     }
 }
 /**
  * testPostmarkSend method
  *
  * @return void
  */
 public function testPostmarkSend()
 {
     $this->email->config('postmark');
     $this->email->template('default', 'default');
     $this->email->emailFormat('html');
     $this->email->from(array('*****@*****.**' => 'Your Name'));
     $this->email->to(array('*****@*****.**' => 'Recipient'));
     $this->email->cc(array('*****@*****.**' => 'Recipient'));
     $this->email->bcc(array('*****@*****.**' => 'Recipient'));
     $this->email->subject('Test Postmark');
     $this->email->addHeaders(array('Tag' => 'my tag'));
     $this->email->attachments(array('cake.icon.png' => array('file' => WWW_ROOT . 'img' . DS . 'cake.icon.png')));
     $sendReturn = $this->email->send();
     $headers = $this->email->getHeaders(array('to'));
     $this->assertEqual($sendReturn['To'], $headers['To']);
     $this->assertEqual($sendReturn['ErrorCode'], 0);
     $this->assertEqual($sendReturn['Message'], 'OK');
 }
 /**
  * Reads attached files and adds them to the data
  *
  * @return void 
  */
 protected function _prepareAttachments()
 {
     $attachments = $this->_cakeEmail->attachments();
     if (empty($attachments)) {
         return;
     }
     foreach ($attachments as $filename => $info) {
         $content = $this->_readFile($info['file']);
         $this->_data['attachments'][$filename] = array('content' => $content, 'Content_type' => $info['mimetype']);
     }
 }
 /**
  * Build message
  *
  * @return array
  */
 private function __buildMessage()
 {
     // Message
     $json = array();
     $json["key"] = $this->_config['key'];
     $message = array();
     // From
     $fromEmail = $this->_cakeEmail->from();
     reset($fromEmail);
     $message['from_email'] = key($fromEmail);
     if ($message['from_email'] != current($fromEmail)) {
         $message['from_name'] = current($fromEmail);
     }
     // To
     $message["to"] = array(array("email" => $this->_headers['To']));
     // Subject
     $message['subject'] = mb_decode_mimeheader($this->_headers['Subject']);
     //Template Name
     if (isset($this->_config['mandrillTemplate']) && !empty($this->_config['mandrillTemplate'])) {
         $json['template_name'] = $this->_config['mandrillTemplate'];
         $json['template_content'] = '';
         //Template Variables -> Merge Variables in Mandrill
         $vars = $this->_cakeEmail->viewVars();
         if (!empty($vars)) {
             $message['global_merge_vars'] = array();
             foreach ($vars as $key => $var) {
                 $message['global_merge_vars'][] = array('name' => $key, 'content' => $var);
             }
         }
     }
     // HtmlBody
     if ($this->_cakeEmail->emailFormat() === 'html' || $this->_cakeEmail->emailFormat() === 'both') {
         $message['html'] = $this->_cakeEmail->message('html');
     }
     // TextBody
     if ($this->_cakeEmail->emailFormat() === 'text' || $this->_cakeEmail->emailFormat() === 'both') {
         $message['text'] = $this->_cakeEmail->message('text');
     }
     $attachments = $this->_cakeEmail->attachments();
     $messageAttachments = array();
     if (!empty($attachments)) {
         foreach ($attachments as $key => $attachment) {
             $content = file_get_contents($attachment['file']);
             $content = base64_encode($content);
             $messageAttachments[] = array('type' => $attachment['mimetype'], 'name' => $key, 'content' => $content);
         }
         if (!empty($messageAttachments)) {
             $message['attachments'] = $messageAttachments;
         }
     }
     $json["message"] = $message;
     return $json;
 }
Beispiel #12
0
 /**
  * Build attachments
  *
  * @return array
  */
 private function __buildAttachments()
 {
     // Attachments
     $attachments = array();
     $i = 0;
     foreach ($this->_cakeEmail->attachments() as $fileName => $fileInfo) {
         $handle = fopen($fileInfo['file'], 'rb');
         $data = fread($handle, filesize($fileInfo['file']));
         $data = chunk_split(base64_encode($data));
         fclose($handle);
         $attachments[$i]['Name'] = $fileName;
         $attachments[$i]['Content'] = $data;
         $attachments[$i]['ContentType'] = $fileInfo['mimetype'];
         $i++;
     }
     return $attachments;
 }
 /**
  * Send
  * 
  * A bit of a misnomer, because this actually just adds it to a CakeResque
  * queue.  The actual sending of the email will be performed later by a worker.
  *
  * @params CakeEmail $email
  * @return array
  */
 public function send(CakeEmail $email)
 {
     // Take a copy of the existing configuration.
     $config = array('headers' => $email->getHeaders(), 'from' => $email->from(), 'sender' => $email->sender(), 'replyTo' => $email->replyTo(), 'readReceipt' => $email->readReceipt(), 'returnPath' => $email->returnPath(), 'to' => $email->to(), 'cc' => $email->cc(), 'bcc' => $email->bcc(), 'subject' => $email->subject(), 'viewRender' => $email->viewRender(), 'viewVars' => $email->viewVars(), 'emailFormat' => $email->emailFormat(), 'messageId' => $email->messageId(), 'attachments' => $email->attachments());
     //        unset($config['config']['transport']);
     $template = $email->template();
     $config['template'] = $template['template'];
     $config['layout'] = $template['layout'];
     // Clean it up to avoid errors.
     $config = array_filter($config, function ($v) {
         return (bool) $v;
     });
     debug($config);
     // Include a message, if they sent one via plain text.
     $message = $email->message(CakeEmail::MESSAGE_HTML) ? null : $email->message(CakeEmail::MESSAGE_TEXT);
     // Drop it in a queue.
     Resque::enqueue('email', 'ResqueEmail.EmailShell', array('send', $config, $message));
     return array('headers' => $email->getHeaders(), 'message' => $email->message());
 }
 /**
  * Sends an email
  * @param  array  $email_data   Email data
  * @param  array $attachments   Attachments data
  * @return boolean              Success of operation
  */
 public function sendMail($email_data = array(), $attachments = null)
 {
     $Email = new CakeEmail();
     $Email->config($email_data['config']);
     $Email->to($email_data['to']);
     if (!is_null($email_data['cc'])) {
         $Email->cc($email_data['cc']);
     }
     $Email->subject($email_data['subject']);
     $Email->emailFormat('html');
     $Email->template($email_data['template'], $email_data['layout']);
     $Email->viewvars($email_data['viewvars']);
     if (!is_null($attachments)) {
         $Email->attachments($attachments);
     }
     if ($Email->send()) {
         return true;
     }
 }
 /**
  * @param $order
  * @param $to
  * @param $filename
  */
 public function sendBill($order, $to, $filename)
 {
     $Email = new CakeEmail('gmail');
     $Email->emailFormat('html');
     $Email->template('order_details_mail')->viewVars(array('order' => $order));
     $Email->to($to);
     $Email->subject('Receipt - MadDollTees');
     $Email->replyTo('*****@*****.**');
     $Email->from('*****@*****.**');
     $Email->attachments('../webroot/pdf/' . $filename . '.pdf');
     $Email->send();
     $Email = new CakeEmail('gmail');
     $Email->emailFormat('html');
     $Email->template('order_details_to_admin')->viewVars(array('order' => $order));
     $Email->to('*****@*****.**');
     $Email->subject('Receipt - MadDollTees');
     $Email->replyTo('*****@*****.**');
     $Email->from('*****@*****.**');
     $Email->attachments('../webroot/pdf/' . $filename . '.pdf');
     $Email->send();
 }
Beispiel #16
0
 /**
      $faktura_id er nummer i tabellen faktura
      $type er navnet på en email template "purring" eller "faktura_melding"
   **/
 function epostPurring($faktura_id, $type)
 {
     $faktura = $this->Faktura->findByNummer($faktura_id);
     $kunde = $faktura['Kunde'];
     $selger = $this->Faktura->Kaffesalg->Selger->findByNummer($faktura['Kaffesalg']['selger_id']);
     $kaffesalg = $this->Faktura->Kaffesalg->findByNummer($faktura['Faktura']['nummer']);
     if (is_string($kunde['epost']) && strlen($kunde['epost']) > 3) {
         $tcpdf = $this->Faktura->lagFakturaTcpdf($faktura, $kaffesalg);
         $filnavn = "faktura" . $faktura['Faktura']['nummer'] . ".pdf";
         $mappe = new Folder();
         $mappesti = $mappe->pwd();
         $absolutt_filnavn = $mappesti . "/" . $filnavn;
         $tcpdf->Output($absolutt_filnavn, "F");
         $pdf_fil = new File($absolutt_filnavn);
         if (!$pdf_fil->exists()) {
             echo "Kunne ikkje lage pdf faktura!";
             return false;
         }
         $email = new CakeEmail('default');
         $email->viewVars(array('navn' => $kunde['navn'], 'faktura' => $faktura, 'kaffesalg' => $kaffesalg, 'selgerNavn' => $selger['Selger']['navn'], 'fakturaDato' => $faktura['Faktura']['faktura_dato'], 'fakturaNr' => $faktura['Faktura']['nummer'], 'fakturaTekst' => $faktura['Faktura']['tekst'], 'betalingsFrist' => $faktura['Faktura']['betalings_frist'], 'epost' => $kunde['epost']));
         $email->template($type, 'vanlig')->emailFormat('both')->to($kunde['epost'])->bcc("*****@*****.**");
         if ($type == "purring") {
             $email->subject("Purring frå zapatistgruppa");
         } else {
             $email->subject("Om kaffien frå zapatistgruppa");
         }
         $email->attachments($absolutt_filnavn)->send();
         $pdf_fil->delete();
         $purring = array('Purring' => array('faktura' => $faktura_id, 'tekst' => 'Automatisk epost-purring: ' . $type, 'sendt' => date('c')));
         $this->create($purring);
         $this->save($this->data);
         return true;
     } else {
         return false;
     }
 }
Beispiel #17
0
 /**
  * Share by e-mail method
  *
  * @param string $id
  * @param string $email
  * @param string $extension
  */
 public function share($id, $email, $extension)
 {
     if (!$this->Book->exists($id)) {
         throw new NotFoundException(__('Invalid book'));
     }
     if (!$extension) {
         throw new NotFoundException(__('Invalid extension'));
     }
     $extension = strtolower($extension);
     $options = array('conditions' => array('Book.' . $this->Book->primaryKey => $id), 'recursive' => 1);
     $book = $this->Book->find('first', $options);
     $fileName = '';
     foreach ($book['Datum'] as $file) {
         if ($file['format'] == strtoupper($extension)) {
             $fileName = $file['name'];
         }
     }
     if (!$fileName) {
         throw new NotFoundException(__('Invalid file name or extension'));
     }
     // We got the file, so send it by e-mail to $email
     $mail = new CakeEmail();
     $mail->config('default');
     $mail->to($email);
     $mail->subject($book['Book']['title']);
     $mail->attachments($this->Book->getCalibrePath() . $book['Book']['path'] . DS . $fileName . '.' . $extension);
     $mail->send();
     $this->autoRender = false;
     return json_encode(array("result" => true));
 }
 public function send($data)
 {
     $this->create(null);
     $this->set($data);
     $Invoice = ClassRegistry::init('LilInvoices.Invoice');
     $Vat = ClassRegistry::init('LilInvoices.Vat');
     $vats = $Vat->findList();
     if ($this->validates() && ($invoices = $Invoice->find('all', array('conditions' => array('Invoice.id' => $data['InvoiceEmail']['invoices']), 'contain' => array('InvoicesItem', 'InvoicesCounter', 'Client' => 'PrimaryAddress', 'InvoicesAttachment', 'InvoicesTax' => 'Vat'))))) {
         // generate PDF
         App::uses('LilReport', 'Lil.Lib');
         App::uses('Sanitize', 'Utility');
         $report = new LilReport();
         $report->helpers(array('Lil.Lil', 'Lil.LilDate', 'Lil.LilFloat', 'Html'));
         $report->template('', 'LilInvoices.lil_invoices_pdf');
         $report->set(array('vats' => $vats));
         $page = 0;
         foreach ($invoices as $i) {
             if ($page > 0) {
                 $report->addPage();
             }
             $report->set(array('data' => $i));
             $report->render(null, array('template' => $i['InvoicesCounter']['layout']));
             $page++;
         }
         $filename = 'invoices_' . strftime('%Y%m%d%H%M%S');
         $report->output(TMP . $filename, 'F');
         // init and send email
         App::uses('CakeEmail', 'Network/Email');
         $email = new CakeEmail();
         $email->template('LilInvoices.send_invoice');
         $email->from(Configure::read('Lil.from.email'), Configure::read('Lil.from.name'));
         $email->returnPath(Configure::read('Lil.from.email'));
         $email->subject($data['InvoiceEmail']['subject']);
         $email->to($data['InvoiceEmail']['to']);
         if (!empty($data['InvoiceEmail']['cc']) && $data['InvoiceEmail']['cc'] != $data['InvoiceEmail']['to']) {
             $email->cc($data['InvoiceEmail']['cc']);
         }
         Cache::write('LilInvoices.emailCacheSubject', $data['InvoiceEmail']['subject'], 'Lil');
         Cache::write('LilInvoices.emailCacheBody', $data['InvoiceEmail']['body'], 'Lil');
         Cache::write('LilInvoices.emailCacheCC', $data['InvoiceEmail']['cc'], 'Lil');
         if (isset($data['InvoiceEmail']['cc_me'])) {
             Cache::write('LilInvoices.emailCacheCCMe', $data['InvoiceEmail']['cc_me'], 'Lil');
         }
         Cache::write('LilInvoices.emailCacheTo', $data['InvoiceEmail']['to'], 'Lil');
         $email->viewVars(array('body' => $data['InvoiceEmail']['body'], 'invoices' => $invoices));
         $ats = array($filename . '.pdf' => array('file' => TMP . $filename . '.pdf', 'mimetype' => 'application/pdf'));
         App::uses('Sanitize', 'Utility');
         foreach ($invoices as $i) {
             foreach ($i['InvoicesAttachment'] as $atch) {
                 $atch_name = 'at_' . $i['Invoice']['no'] . '_' . $atch['original'];
                 $atch_file = APP . 'uploads' . DS . 'Invoice' . DS . $atch['filename'];
                 if (file_exists($atch_file)) {
                     $ats[Sanitize::paranoid($atch_name, array('-', '_', '.'))] = array('file' => $atch_file, 'mimetype' => $atch['mimetype']);
                 }
             }
         }
         $email->attachments($ats);
         $result = $email->send();
         unlink(TMP . $filename . '.pdf');
         return $result;
     }
     return false;
 }
    function payslip_update()
    {
        if ($this->request->data) {
            $this->set('employee_id', $this->request->data['SalaryRecord']['employee_id']);
            $res = $this->Employee->SalaryRecord->salarySearch($this->request->data['SalaryRecord']['employee_id'], $this->request->data['SalaryRecord']['salary_date']);
            if ($res['SalaryRecord']['payslip_generated'] != 1) {
                //debug($this->request->data);
                $earnings = $this->request->data['SalaryRecord']['basic'] + $this->request->data['SalaryRecord']['da'] + $this->request->data['SalaryRecord']['bonus'] + $this->request->data['SalaryRecord']['medical_allowance'] + $this->request->data['SalaryRecord']['tiffin'] + $this->request->data['SalaryRecord']['house_rent'] + $this->request->data['SalaryRecord']['education'] + $this->request->data['SalaryRecord']['entertainment'];
                $deductions = $this->request->data['SalaryRecord']['pf'] + $this->request->data['SalaryRecord']['esi'] + $this->request->data['SalaryRecord']['income_tax'];
                $this->request->data['SalaryRecord']['net_salary'] = $earnings - $deductions;
                $se = $this->Session->read("Auth");
                $this->request->data['SalaryRecord']['user_id'] = $se['User']['id'];
                $this->request->data['SalaryRecord']['print_copy'] = 1;
                $this->request->data['SalaryRecord']['payslip_generated'] = 1;
                //debug($this->request->data['SalaryRecord']);exit();
                if ($res['SalaryRecord']['id']) {
                    $this->Employee->SalaryRecord->id = $res['SalaryRecord']['id'];
                } else {
                    $this->Employee->SalaryRecord->create();
                }
                if ($this->Employee->SalaryRecord->save($this->request->data)) {
                    //update the loan amount
                    if ($this->request->data['SalaryRecord']['loan_amount'] > 0) {
                        $this->request->data['Loan']['loan_amount'] = $this->request->data['SalaryRecord']['loan_amount'];
                        $this->request->data['Loan']['employee_id'] = $this->request->data['SalaryRecord']['employee_id'];
                        $loan_save = $this->Employee->Loan->loanEntryUpdate($this->request->data['Loan']);
                    }
                    $this->set('salary_saved', 1);
                    $name = $this->request->data['SalaryRecord']['fname'];
                    if ($this->request->data['SalaryRecord']['mname'] != null) {
                        $name .= ' ' . $this->request->data['SalaryRecord']['mname'];
                    }
                    $name .= ' ' . $this->request->data['SalaryRecord']['lname'];
                    App::import('Vendor', 'xtcpdf');
                    $tcpdf = new XTCPDF();
                    $textfont = 'freesans';
                    // looks better, finer, and more condensed than 'dejavusans'
                    $tcpdf->SetAuthor("Company Name");
                    $tcpdf->SetAutoPageBreak(false);
                    $tcpdf->setPrintHeader(false);
                    $tcpdf->setPrintFooter(false);
                    //$tcpdf->setHeaderFont(array($textfont,'',40));
                    //$tcpdf->xheadercolor = array(0,0,0);
                    //$tcpdf->xheadertext = '';
                    //$tcpdf->xfootertext = '';
                    // add a page (required with recent versions of tcpdf)
                    $tcpdf->AddPage();
                    // Now you position and print your page content
                    // example:
                    $fill = 0;
                    $tcpdf->SetTextColor(0, 0, 0);
                    $tcpdf->SetFont($textfont, 'B', 20);
                    $header_html = '<span>Company Logo</span>';
                    $header_html2 = '<span>Company Address</span>';
                    $payslip_date = '<p style="font-size:20px!important">Playslip for the month of ' . $this->request->data['SalaryRecord']['salary_date'] . '</p>';
                    $emp_name = '<p style="font-size:20px!important">Name : ' . $name . '</p>';
                    $employee_id = '<p style="font-size:20px!important">Employee Id : emp' . $this->request->data['SalaryRecord']['employee_id'] . '</p>';
                    $department = '<p style="font-size:20px!important">Department : ' . $this->request->data['SalaryRecord']['department'] . '</p>';
                    $designation = '<p style="font-size:20px!important">Designation : ' . $this->request->data['SalaryRecord']['designation'] . '</p>';
                    $employee = $this->Employee->employeeSearch($this->request->data['SalaryRecord']['employee_id']);
                    $expected_earnings = $employee['Employee']['net_salary'] + $employee['Employee']['da'] + $employee['Employee']['bonus'] + $employee['Employee']['medical_allowance'] + $employee['Employee']['tiffin'] + $employee['Employee']['house_rent'] + $employee['Employee']['education'] + $employee['Employee']['entertainment'];
                    $expected_deductions = $employee['Employee']['pf'] + $employee['Employee']['esi'] + $employee['Employee']['income_tax'];
                    $earnings_content = '
<style>
	table{width:100%;border:none}
	th{font-size:12px;height:10px;font-size:22px!important;border-bottom:0px solid black}
	td{font-size:20px!important;width:100%;}
	.total{border-top:0px solid black}
</style>
<table>
 <tr>
  <th><b>Earnings</b></th>
 </tr>
 <tr>
 <td width="50%"></td>
  <td width="25%">Full (Rs.)</td>
  <td width="25%">Actual (Rs.)</td>
 </tr>
 <tr>
 <td width="50%">Basic</td>
  <td width="25%">' . $employee['Employee']['net_salary'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['basic'] . '</td>
 </tr>
 <tr>
  <td width="50%">DA</td>
  <td width="25%">' . $employee['Employee']['da'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['da'] . '</td>
 </tr>
 <tr>
  <td width="50%">Bonus</td>
  <td width="25%">' . $employee['Employee']['bonus'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['bonus'] . '</td>
 </tr>
 <tr>
  <td width="50%">Medical Allowance</td>
  <td width="25%">' . $employee['Employee']['medical_allowance'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['medical_allowance'] . '</td>
 </tr>
  <tr>
  <td width="50%">Tiffin Allowance</td>
  <td width="25%">' . $employee['Employee']['tiffin'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['tiffin'] . '</td>
 </tr>
  <tr>
  <td width="50%">House Rent Allowance</td>
  <td width="25%">' . $employee['Employee']['house_rent'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['house_rent'] . '</td>
 </tr>
 <tr>
  <td width="50%">Education Allowance</td>
  <td width="25%">' . $employee['Employee']['education'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['education'] . '</td>
 </tr>
  <tr>
  <td width="50%">Entertainment Allowance</td>
  <td width="25%">' . $employee['Employee']['entertainment'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['entertainment'] . '</td>
 </tr>
 <tr>
  <td width="50%"  class="total"><b>Total Earnings (Rs.) :</b></td>
  <td width="25%"  class="total"><b>' . $expected_earnings . '</b></td>
  <td width="25%"  class="total"><b>' . $earnings . '</b></td>
 </tr>
	 </table>';
                    $deductions_content = '
<style>
	table{width:100%;border:none}
	th{font-size:12px;height:10px;font-size:22px!important;border-bottom:0px solid black}
	td{font-size:20px!important;width:100%;}
	.total{border-top:0px solid black}

</style>
<table>
 <tr>
  <th><b>Deductions</b></th>
 </tr>
 <tr>
 <td width="50%"></td>
  <td width="25%">Full (Rs.)</td>
  <td width="25%">Actual (Rs.)</td>
 </tr>
 <tr>
 <td width="50%">PF</td>
  <td width="25%">' . $employee['Employee']['pf'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['pf'] . '</td>
 </tr>
 <tr>
  <td width="50%">ESI</td>
  <td width="25%">' . $employee['Employee']['esi'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['esi'] . '</td>
 </tr>
 <tr>
  <td width="50%">TDS</td>
  <td width="25%">' . $employee['Employee']['income_tax'] . '</td>
  <td width="25%">' . $this->request->data['SalaryRecord']['income_tax'] . '</td>
 </tr>
  <tr>
  <td width="50%">Advance</td>
  <td width="25%">0</td>
  <td width="25%">0</td>
 </tr>
  <tr>
  <td width="50%">Loan</td>
  <td width="25%">0</td>
  <td width="25%">0</td>
 </tr>
 <tr>
  <td width="50%"></td>
  <td width="25%"></td>
  <td width="25%"></td>
 </tr>
 <tr>
  <td width="50%"></td>
  <td width="25%"></td>
  <td width="25%"></td>
 </tr>
 <tr>
  <td width="50%"></td>
  <td width="25%"></td>
  <td width="25%"></td>
 </tr>
 <tr>
  <td width="50%"  class="total"><b>Total Deductions (Rs.) :</b></td>
  <td width="25%"  class="total"><b>' . $expected_deductions . '</b></td>
  <td width="25%"  class="total"><b>' . $deductions . '</b></td>
 </tr>
	 </table>';
                    $net_earnings = $earnings - $deductions;
                    $net_salary = '<p style="font-size:20px!important"><b>Net Salary : Rs. ' . $net_earnings . '</b></p>';
                    $auto_text = '<p style="font-size:22px!important;color:#cccccc">This is a computer-generated salary slip. Does not require a Signature</p>';
                    $tcpdf->SetFillColor(155, 100, 0);
                    $tcpdf->writeHTMLCell(50, 0, '', 10, $header_html, 0, 1, 0, true, 'L', true);
                    $tcpdf->writeHTMLCell(50, 0, 55, 10, $header_html2, 0, 0, 0, true, 'R', true);
                    $tcpdf->writeHTMLCell(0, 0, '', 35, $payslip_date, 0, 1, 0, true, 'L', true);
                    $tcpdf->writeHTMLCell(80, 5, '', 40, $emp_name, 'LRTB', 1, 0, true, 'C', true);
                    $tcpdf->writeHTMLCell(80, 5, 85, 40, $employee_id, 'RTB', 1, 0, true, 'C', true);
                    $tcpdf->writeHTMLCell(80, 5, '', 45, $department, 'LRB', 1, 0, true, 'C', true);
                    $tcpdf->writeHTMLCell(80, 5, 85, 45, $designation, 'RB', 1, 0, true, 'C', true);
                    $tcpdf->writeHTMLCell(80, '', '', 55, $earnings_content, 'LRTB', 1, 0, true, 'C', true);
                    $tcpdf->writeHTMLCell(80, '', 85, 55, $deductions_content, 'RTB', 1, 0, true, 'C', true);
                    $tcpdf->writeHTMLCell(155, 3, '', '', $net_salary, 'LRTB', 1, 0, true, 'L', true);
                    $tcpdf->writeHTMLCell(155, '', '', 105, $auto_text, '', 1, 0, true, 'L', true);
                    // ...
                    // etc.
                    // see the TCPDF examples
                    $file_name = time() . '.pdf';
                    echo $tcpdf->Output($file_name, 'F');
                    //setting view variables before sending email so that if email is not sent generated salry slip will still be viewed
                    $this->set('salaryrecord', $this->request->data['SalaryRecord']);
                    $this->set('employee', $employee);
                    $this->set('earnings', $earnings);
                    $this->set('deductions', $deductions);
                    $this->set('expected_earnings', $expected_earnings);
                    $this->set('net_earnings', $net_earnings);
                    App::uses('CakeEmail', 'Network/Email');
                    $Email = new CakeEmail();
                    $Email->to($this->request->data['SalaryRecord']['email']);
                    $Email->bcc($se['User']['email']);
                    $Email->subject('Salary Slip of ' . $name . ' [ emp' . $this->request->data['SalaryRecord']['employee_id'] . ' ] for ' . $this->request->data['SalaryRecord']['salary_date']);
                    $Email->replyTo($se['User']['email']);
                    $Email->from($se['User']['email']);
                    $Email->emailFormat('html');
                    $Email->viewVars(array('salary_record' => $this->request->data['SalaryRecord']));
                    $Email->attachments($file_name);
                    $Email->template('salaryslip');
                    //$Email->send();
                    App::uses('File', 'Utility');
                    $file = new File($file_name);
                    $file->delete();
                } else {
                    $this->set('salary_saved', 0);
                }
            }
        }
    }
 public function forgottenPassword()
 {
     if ($this->request->is('post')) {
         $this->User->set($this->request->data);
         if ($this->User->validates()) {
             $user = $this->User->find('first', array('conditions' => array('User.username' => $this->request->data['User']['verif_username'], 'User.mail' => $this->request->data['User']['verif_mail'])));
             if (!empty($user)) {
                 $token = array('User' => array('token' => bin2hex(openssl_random_pseudo_bytes(20))));
                 $this->User->id = $user['User']['id'];
                 $this->User->save($token);
                 $newUser = $this->User->findById($user['User']['id']);
                 App::uses('CakeEmail', 'Network/Email');
                 $Email = new CakeEmail('smtp');
                 $Email->viewVars(array('mailData' => $newUser));
                 $Email->template('newPassword', 'default');
                 $Email->emailFormat('html');
                 $Email->from(array('*****@*****.**' => 'YouthBook.be'));
                 $Email->to($this->request->data['User']['verif_mail']);
                 $Email->subject('Mot de passe oublié');
                 $Email->attachments(array('logo.png' => array('file' => WWW_ROOT . '/img/icons/logo.png', 'mimetype' => 'image/png', 'contentId' => 'logo')));
                 $Email->send();
                 $this->Flash->success(__('Votre demande a bien été envoyée.'));
                 return $this->redirect($this->referer());
             } else {
                 $this->Flash->error('Cet utilisateur n’existe pas. Veuillez réessayer SVP.');
             }
         } else {
             $this->Flash->error('La demande n’a pas pu être envoyé. Veuillez réessayer SVP.');
         }
     }
 }
 function sendMailWithAttachment($template = 'default', $to_email = null, $from_email = null, $subject = '', $contents = '', $file = null)
 {
     App::uses('CakeEmail', 'Network/Email');
     $my_mail = new CakeEmail();
     $my_mail->template($template);
     $my_mail->emailFormat('html');
     $my_mail->helpers(array('Html'));
     $my_mail->from(array($from_email => $contents['sender']));
     $my_mail->to($to_email);
     $my_mail->subject($subject);
     $my_mail->viewVars(array('contents' => $contents));
     if ($file) {
         $my_mail->attachments(array($file['name'] => $file['tmp_name']));
     }
     if ($my_mail->send()) {
         return true;
     }
     return false;
 }
    public function sendMail($dados)
    {
        App::uses('CakeEmail', 'Network/Email');
        $email = new CakeEmail('default');
        $email->from('*****@*****.**', 'OdontoClinic Pimentas')->to($dados['email'])->subject('Newsletter OdontoClinic Pimentas');
        $mensagem = 'Obrigado pelo cadastro, em breve você vai receber novidades e promoções!';
        if (file_exists(APP . 'webroot/odontoclinicpimentas/ebooks/' . $dados['origem'] . '.pdf')) {
            $email->attachments(APP . '/webroot/odontoclinicpimentas/ebooks/' . $dados['origem'] . '.pdf');
            $mensagem = '
				Obrigado pelo cadastro, para mais informações veja o arquivo em anexo!
			';
        }
        $mensagem .= "\n OdontoClinic Pimentas\n\t\t\t\t\t\n Rua 7, 23\n\t\t\t\t\t\n Jardim Nova Cidade, 07252-380\n\t\t\t\t\t\n (11) 2486-8936";
        $email->send($mensagem);
        return $this->response->body('{"message": "success", "result":' . json_encode($dados) . '}');
    }
Beispiel #23
0
 /**
  * メールを送信する
  *
  * @param string $to 送信先アドレス
  * @param string $title タイトル
  * @param mixed $body 本文
  * @param array $options オプション
  * @return bool 送信結果
  */
 public function sendMail($to, $title = '', $body = '', $options = array())
 {
     $options = array_merge(array('agentTemplate' => true, 'template' => 'default'), $options);
     if (!empty($this->siteConfigs['smtp_host'])) {
         $transport = 'Smtp';
         $host = $this->siteConfigs['smtp_host'];
         $port = $this->siteConfigs['smtp_port'] ? $this->siteConfigs['smtp_port'] : 25;
         $username = $this->siteConfigs['smtp_user'] ? $this->siteConfigs['smtp_user'] : null;
         $password = $this->siteConfigs['smtp_password'] ? $this->siteConfigs['smtp_password'] : null;
         $tls = $this->siteConfigs['smtp_tls'] && $this->siteConfigs['smtp_tls'] == 1;
     } else {
         $transport = 'Mail';
         $host = 'localhost';
         $port = 25;
         $username = null;
         $password = null;
         $tls = null;
     }
     $config = array('transport' => $transport, 'host' => $host, 'port' => $port, 'username' => $username, 'password' => $password, 'tls' => $tls);
     $cakeEmail = new CakeEmail($config);
     // charset
     if (!empty($this->siteConfigs['mail_encode'])) {
         $encode = $this->siteConfigs['mail_encode'];
     } else {
         $encode = 'ISO-2022-JP';
     }
     // ISO-2022-JPの場合半角カナが文字化けしてしまうので全角に変換する
     if ($encode == 'ISO-2022-JP') {
         $title = mb_convert_kana($title, 'KV', "UTF-8");
         if (is_string($body)) {
             $body = mb_convert_kana($body, 'KV', "UTF-8");
         } elseif (isset($body['message']) && is_array($body['message'])) {
             foreach ($body['message'] as $key => $val) {
                 if (is_string($val)) {
                     $body['message'][$key] = mb_convert_kana($val, 'KV', "UTF-8");
                 }
             }
         }
     }
     //CakeEmailの内部処理のencodeを統一したいので先に値を渡しておく
     $cakeEmail->headerCharset($encode);
     $cakeEmail->charset($encode);
     //$format
     if (!empty($options['format'])) {
         $cakeEmail->emailFormat($options['format']);
     } else {
         $cakeEmail->emailFormat('text');
     }
     //bcc 'mail@example.com,mail2@example.com'
     if (!empty($options['bcc'])) {
         // 文字列の場合
         $bcc = array();
         if (is_string($options['bcc'])) {
             if (strpos($options['bcc'], ',') !== false) {
                 $bcc = explode(',', $options['bcc']);
             } else {
                 $bcc[] = $options['bcc'];
             }
             // 配列の場合
         } elseif (is_array($options['bcc'])) {
             $bcc = $options['bcc'];
         }
         foreach ($bcc as $val) {
             if (Validation::email(trim($val))) {
                 $cakeEmail->addBcc($val);
             }
         }
         unset($bcc);
     }
     //cc 'mail@example.com,mail2@example.com'
     if (!empty($options['cc'])) {
         // 文字列の場合
         $cc = array();
         if (is_string($options['cc'])) {
             if (strpos($options['cc'], ',') !== false) {
                 $cc = explode(',', $options['cc']);
             } else {
                 $cc[] = $options['cc'];
             }
             // 配列の場合
         } elseif (is_array($options['cc'])) {
             $cc = $options['cc'];
         }
         foreach ($cc as $val) {
             if (Validation::email(trim($val))) {
                 $cakeEmail->addCc($val);
             }
         }
         unset($cc);
     }
     // to 送信先アドレス (最初の1人がTOで残りがBCC)
     if (strpos($to, ',') !== false) {
         $_to = explode(',', $to);
         $i = 0;
         if (count($_to) >= 1) {
             foreach ($_to as $val) {
                 if ($i == 0) {
                     $cakeEmail->addTo($val);
                     $toAddress = $val;
                 } else {
                     $cakeEmail->addBcc($val);
                 }
                 ++$i;
             }
         }
     } else {
         $cakeEmail->addTo($to);
     }
     // 件名
     $cakeEmail->subject($title);
     //From
     $fromName = $from = '';
     if (!empty($options['from'])) {
         $from = $options['from'];
     } else {
         if (!empty($this->siteConfigs['email'])) {
             $from = $this->siteConfigs['email'];
             if (strpos($from, ',') !== false) {
                 $from = explode(',', $from);
             }
         } else {
             $from = $toAddress;
         }
     }
     if (!empty($options['fromName'])) {
         $fromName = $options['fromName'];
     } else {
         if (!empty($this->siteConfigs['formal_name'])) {
             $fromName = $this->siteConfigs['formal_name'];
         } else {
             $formalName = Configure::read('BcApp.title');
         }
     }
     $cakeEmail->from($from, $fromName);
     //Reply-To
     if (!empty($options['replyTo'])) {
         $replyTo = $options['replyTo'];
     } else {
         $replyTo = $from;
     }
     $cakeEmail->replyTo($replyTo);
     //Return-Path
     if (!empty($options['returnPath'])) {
         $returnPath = $options['returnPath'];
     } else {
         $returnPath = $from;
     }
     $cakeEmail->returnPath($returnPath);
     //$sender
     if (!empty($options['sender'])) {
         $cakeEmail->sender($options['sender']);
     }
     //$theme
     if ($this->theme) {
         $cakeEmail->theme($this->theme);
     }
     if (!empty($options['theme'])) {
         $cakeEmail->theme($options['theme']);
     }
     //viewRender (利用するviewクラスを設定する)
     $cakeEmail->viewRender('BcApp');
     //template
     if (!empty($options['template'])) {
         $layoutPath = $subDir = $plugin = '';
         if ($options['agentTemplate'] && Configure::read('BcRequest.agent')) {
             $layoutPath = Configure::read('BcRequest.agentPrefix');
             $subDir = Configure::read('BcRequest.agentPrefix');
         }
         list($plugin, $template) = pluginSplit($options['template']);
         if ($subDir) {
             $template = "{$subDir}/{$template}";
         }
         if (!empty($plugin)) {
             $template = "{$plugin}.{$template}";
         }
         if (!empty($options['layout'])) {
             $cakeEmail->template($template, $options['layout']);
         } else {
             $cakeEmail->template($template);
         }
         $content = '';
         if (is_array($body)) {
             $cakeEmail->viewVars($body);
         } else {
             $cakeEmail->viewVars(array('body' => $body));
         }
     } else {
         $content = $body;
     }
     // $attachments tmp file path
     $attachments = array();
     if (!empty($options['attachments'])) {
         if (!is_array($options['attachments'])) {
             $attachments = array($options['attachments']);
         } else {
             $attachments = $options['attachments'];
         }
     }
     $cakeEmail->attachments($attachments);
     try {
         $cakeEmail->send($content);
         return true;
     } catch (Exception $e) {
         $this->log($e->getMessage());
         return false;
     }
 }
 function downloadConfrontationData($tableName = null, $sendByMail = null)
 {
     $this->autoRender = false;
     $confrontationResult = $this->Session->read('confrontationResult');
     $confrontationSettingsData = $this->Session->read('confrontationSettingsData');
     $confrontationDualResult = $this->Session->read('confrontationDualResult');
     $confrontationData = $this->Session->read('confrontationPostedData');
     /* aunque no haya nada ponemos valores igualmente */
     if (empty($confrontationResult)) {
         $confrontationResult = 'null';
     }
     if (empty($confrontationSettingsData)) {
         $confrontationSettingsData = 'null';
     }
     if (empty($confrontationDualResult)) {
         $confrontationDualResult = 'null';
     }
     if (empty($confrontationData)) {
         $confrontationData = 'null';
     }
     $dataText = json_encode(array("confrontationResult" => $confrontationResult, "confrontationSettingsData" => $confrontationSettingsData, "confrontationDualResult" => $confrontationDualResult, "confrontationPostedData" => $confrontationData, "tableToLoad" => $tableName));
     $dataText = Security::cipher($dataText, Configure::read('Security.salt'));
     $fileName = "MarkyData-" . $tableName . "__" . date("Y-m-d") . ".json";
     if ($sendByMail != null) {
         $emailProfile = Configure::read('emailProfile');
         $Email = new CakeEmail($emailProfile);
         $Email->from(array('*****@*****.**' => 'Marky'));
         $userMail = $sendByMail['email'];
         $userName = $sendByMail['username'];
         $Email->to($userMail);
         $Email->subject('Marky agreement statistics');
         $Email->emailFormat('html');
         $Email->template('sendData');
         $Email->viewVars(array('userName' => $userName));
         $tmpfname = tempnam(sys_get_temp_dir(), "sendData");
         $file = new File($tmpfname, true, 0777);
         if ($file->append($dataText)) {
             $Email->attachments(array($fileName => array('file' => $file->pwd())));
             $file->close();
             if (!$Email->send("")) {
                 CakeLog::write('MailLog', 'Error send  statistics to: ' . $sendByMail['email']);
             }
         } else {
             CakeLog::write('MailLog', 'CRASH:Append statistics to send to: ' . $sendByMail['email']);
             $file->delete();
             throw new Exception("Append data to send -> crash", 1);
         }
         $file->delete();
     } else {
         $this->response->type('txt');
         $this->response->body($dataText);
         $this->response->download($fileName);
     }
 }
Beispiel #25
0
 public function sendMailWithAttachment($to, $file, $subject, $contents, $msg)
 {
     $email = new CakeEmail('smtp');
     $email->sendAs = 'text';
     $email->delivery = 'smtp';
     $email->subject($subject);
     $email->to($to);
     $email->helpers(array("Html"));
     $email->template("default");
     $email->emailFormat("html");
     $email->attachments($file);
     $email->viewVars($contents);
     if ($email->send($msg)) {
         return true;
     }
     return false;
 }
 public function deploy($id = nulll)
 {
     $cmpgn = $this->Campaign->find('first', array('conditions' => array('Campaign.id' => $id)));
     if ($this->request->is('post')) {
         if ($cmpgn['Campaign']['deployed']) {
             $this->Flash->error(__('This campaign is already Deployed!'));
             $this->redirect(array('action' => 'view/' . $id));
         } else {
             $db = ConnectionManager::getDataSource('default');
             $participants = $db->fetchAll('SELECT email from customers');
             $fname = 'campaign' . $cmpgn['Campaign']['id'] . '.ctp';
             $file = new File('app/View/Pages/' . $fname, true);
             echo strrchr($file->read(), '.jpg');
             die;
             foreach ($participants as $participant) {
                 $db->query("INSERT INTO participants (campaign_id, participant_id) VALUES({$id}, '" . $participant[0]['email'] . "')");
                 $Email = new CakeEmail();
                 $Email->config('gmail');
                 $Email->to($participant[0]['email'])->subject($cmpgn['Campaign']['name']);
                 if ($cmpgn['Campaign']['type'] == 'Re-tweeting Promotion') {
                     $Email->attachments(array('Promotion.jpg' => 'app/webroot/img/campaigns/c' . $id . '.jpg'));
                     $Email->send(strip_tags($file->read()) . ' Hashtag: ' . $cmpgn['Campaign']['hashtag']);
                 } else {
                     $Email->send('We are holding another amazing Recommend for Reward campaign! Please Share this link with your friends and families and keep increasing your reward NOW! http://localhost:8080/pages/campaign' . $id . '/' . $db->lastInsertId());
                 }
             }
             $this->Flash->success(__('The campaign successifully deployed to all customers!'));
             $this->Campaign->id = $id;
             $this->Campaign->save(array('Campaign' => ['deployed' => true]));
             $this->redirect(array('action' => 'view/' . $id));
         }
     }
 }
Beispiel #27
0
 public function sendEmail($user, $body, $bodyNoEnc = false, $subject, $replyToUser = false)
 {
     $failed = false;
     $failureReason = "";
     // check if the e-mail can be encrypted
     $canEncrypt = false;
     if (isset($user['User']['gpgkey']) && !empty($user['User']['gpgkey'])) {
         $canEncrypt = true;
     }
     // If bodyonlencrypted is enabled and the user has no encryption key, use the alternate body (if it exists)
     if (Configure::read('GnuPG.bodyonlyencrypted') && !$canEncrypt && $bodyNoEnc) {
         $body = $bodyNoEnc;
     }
     $body = str_replace('\\n', PHP_EOL, $body);
     // Sign the body
     require_once 'Crypt/GPG.php';
     try {
         $gpg = new Crypt_GPG(array('homedir' => Configure::read('GnuPG.homedir'), 'binary' => Configure::read('GnuPG.binary') ? Configure::read('GnuPG.binary') : '/usr/bin/gpg'));
         // , 'debug' => true
         $gpg->addSignKey(Configure::read('GnuPG.email'), Configure::read('GnuPG.password'));
         $body = $gpg->sign($body, Crypt_GPG::SIGN_MODE_CLEAR);
     } catch (Exception $e) {
         $failureReason = " the message could not be signed. The following error message was returned by gpg: " . $e->getMessage();
         $this->log($e->getMessage());
         $failed = true;
     }
     // If we cannot encrypt the mail and the server settings restricts sending unencrypted messages, return false
     if (!$failed && !$canEncrypt && Configure::read('GnuPG.onlyencrypted')) {
         $failed = true;
         $failureReason = " encrypted messages are enforced and the message could not be encrypted for this user as no valid encryption key was found.";
     }
     // Let's encrypt the message if we can
     if (!$failed && $canEncrypt) {
         $keyImportOutput = $gpg->importKey($user['User']['gpgkey']);
         try {
             $gpg->addEncryptKey($keyImportOutput['fingerprint']);
             // use the key that was given in the import
             $body = $gpg->encrypt($body, true);
         } catch (Exception $e) {
             // despite the user having a PGP key and the signing already succeeding earlier, we get an exception. This must mean that there is an issue with the user's key.
             $failureReason = " the message could not be encrypted because there was an issue with the user's PGP key. The following error message was returned by gpg: " . $e->getMessage();
             $this->log($e->getMessage());
             $failed = true;
         }
     }
     $replyToLog = '';
     if (!$failed) {
         $Email = new CakeEmail();
         // If the e-mail is sent on behalf of a user, then we want the target user to be able to respond to the sender
         // For this reason we should also attach the public key of the sender along with the message (if applicable)
         if ($replyToUser != false) {
             $Email->replyTo($replyToUser['User']['email']);
             if (!empty($replyToUser['User']['gpgkey'])) {
                 $Email->attachments(array('gpgkey.asc' => array('data' => $replyToUser['User']['gpgkey'])));
             }
             $replyToLog = 'from ' . $replyToUser['User']['email'];
         }
         $Email->from(Configure::read('MISP.email'));
         $Email->to($user['User']['email']);
         $Email->subject($subject);
         $Email->emailFormat('text');
         $result = $Email->send($body);
         $Email->reset();
     }
     $this->Log = ClassRegistry::init('Log');
     $this->Log->create();
     if (!$failed && $result) {
         $this->Log->save(array('org' => 'SYSTEM', 'model' => 'User', 'model_id' => $user['User']['id'], 'email' => $user['User']['email'], 'action' => 'email', 'title' => 'Email ' . $replyToLog . ' to ' . $user['User']['email'] . ' sent, titled "' . $subject . '".', 'change' => null));
         return true;
     } else {
         if (isset($result) && !$result) {
             $failureReason = " there was an error sending the e-mail.";
         }
         $this->Log->save(array('org' => 'SYSTEM', 'model' => 'User', 'model_id' => $user['User']['id'], 'email' => $user['User']['email'], 'action' => 'email', 'title' => 'Email ' . $replyToLog . ' to ' . $user['User']['email'] . ', titled "' . $subject . '" failed. Reason: ' . $failureReason, 'change' => null));
     }
     return false;
 }
Beispiel #28
0
 protected function _sendEmail($to, $subject, $message, $attachments = NULL)
 {
     if (YOUNIQUE_TESTSERVER) {
         $subject = "TEST ONLY: " . $subject;
         $to = array('*****@*****.**');
     }
     App::uses('CakeEmail', 'Network/Email');
     $email_transport = "default";
     $email = new CakeEmail($email_transport);
     $email->template('facebooklist', 'default');
     $email->emailFormat('both');
     $email->to($to);
     if ($email_transport != "default") {
         //doesn't work on the default
         $email->from("*****@*****.**");
     }
     $email->subject($subject);
     if (!empty($attachments)) {
         $email->attachments($attachments);
     }
     $email->viewVars(array('message' => $message));
     $email->send();
 }
Beispiel #29
0
/**
 * Send an email using the specified content, template and layout
 *
 * @param string|array $content Either an array of text lines, or a string with contents
 *  If you are rendering a template this variable will be sent to the templates as `$content`
 * @param string $template Template to use when sending email
 * @param string $layout Layout to use to enclose email body
 * @return boolean Success
 */
	public function send($content = null, $template = null, $layout = null) {
		$lib = new CakeEmail();
		$lib->charset = $this->charset;
		$lib->headerCharset = $this->charset;

		$lib->from($this->_formatAddresses((array)$this->from));
		if (!empty($this->to)) {
			$lib->to($this->_formatAddresses((array)$this->to));
		}
		if (!empty($this->cc)) {
			$lib->cc($this->_formatAddresses((array)$this->cc));
		}
		if (!empty($this->bcc)) {
			$lib->bcc($this->_formatAddresses((array)$this->bcc));
		}
		if (!empty($this->replyTo)) {
			$lib->replyTo($this->_formatAddresses((array)$this->replyTo));
		}
		if (!empty($this->return)) {
			$lib->returnPath($this->_formatAddresses((array)$this->return));
		}
		if (!empty($this->readReceipt)) {
			$lib->readReceipt($this->_formatAddresses((array)$this->readReceipt));
		}

		$lib->subject($this->subject)->messageID($this->messageId);
		$lib->helpers($this->_controller->helpers);

		$headers = array('X-Mailer' => $this->xMailer);
		foreach ($this->headers as $key => $value) {
			$headers['X-' . $key] = $value;
		}
		if ($this->date) {
			$headers['Date'] = $this->date;
		}
		$lib->setHeaders($headers);

		if ($template) {
			$this->template = $template;
		}
		if ($layout) {
			$this->layout = $layout;
		}
		$lib->template($this->template, $this->layout)->viewVars($this->_controller->viewVars)->emailFormat($this->sendAs);

		if (!empty($this->attachments)) {
			$lib->attachments($this->_formatAttachFiles());
		}

		$lib->transport(ucfirst($this->delivery));
		if ($this->delivery === 'mail') {
			$lib->config(array('eol' => $this->lineFeed, 'additionalParameters' => $this->additionalParams));
		} elseif ($this->delivery === 'smtp') {
			$lib->config($this->smtpOptions);
		} else {
			$lib->config(array());
		}

		$sent = $lib->send($content);

		$this->htmlMessage = $lib->message(CakeEmail::MESSAGE_HTML);
		if (empty($this->htmlMessage)) {
			$this->htmlMessage = null;
		}
		$this->textMessage = $lib->message(CakeEmail::MESSAGE_TEXT);
		if (empty($this->textMessage)) {
			$this->textMessage = null;
		}

		$this->_header = array();
		$this->_message = array();

		return $sent;
	}
 public function sendMail($mailto, $template, $subject, $code, $user_id)
 {
     $Email = new CakeEmail('gmail');
     $Email->emailFormat('html');
     $Email->to($mailto);
     $Email->template($template)->viewVars(array('code' => $code, 'id' => $user_id));
     $Email->attachments(array('maillogo.png' => array('file' => WWW_ROOT . '/img/maillogo.png', 'mimetype' => 'image/png', 'contentId' => 'logo')));
     $Email->subject($subject);
     $Email->replyTo('*****@*****.**');
     $Email->from('*****@*****.**');
     $Email->send();
 }