Exemple #1
0
 public function submitAction()
 {
     $result = "";
     $contact = $this->params()->fromPost();
     $captcha = new Captcha(array('name' => 'captcha', 'wordLen' => 6, 'timeout' => 600));
     if ($captcha->isValid($_POST['captcha'], $_POST)) {
         unset($contact['submit']);
         $contact = array_filter($contact);
         if ($contact && is_array($contact)) {
             $mail = new Mail\Message();
             $html = '<p>Contact from Kingsy.co.uk</p><p>=-=-=-=-=-=-=-=-=-=-=-=-=-=</p><p><span></span>From: <span>' . $contact["name"] . '</span></p><p><span></span>Email: <span>' . $contact["email"] . '</span></p><p><span></span>Content<p>' . $contact["content"] . '</p></p>';
             $mail->setFrom('*****@*****.**', 'Contact Form - Kingsy.co.uk')->addTo("*****@*****.**")->setSubject('Contacted');
             $bodyPart = new MimeMessage();
             $bodyMessage = new MimePart($html);
             $bodyMessage->type = 'text/html';
             $bodyPart->setParts(array($bodyMessage));
             $mail->setBody($bodyPart);
             $mail->setEncoding('UTF-8');
             try {
                 $transport = new Mail\Transport\Sendmail();
                 $transport->send($mail);
                 $result = true;
             } catch (Exception $e) {
                 print_r($e);
             }
         } else {
             $result = false;
         }
     } else {
         $result = false;
     }
     return new ViewModel(array('result' => $result));
 }
 protected function sendOfflineMessage($msgSubj, $msgText, $fromUserId, $toUserId)
 {
     $userTable = $this->getServiceLocator()->get('UserTable');
     $fromUser = $userTable->getById($fromUserId);
     $toUser = $userTable->getById($toUserId);
     $mail = new Mail\Message();
     $mail->setFrom($fromUser->getEmail(), $fromUser->getName());
     $mail->addTo($toUser->getEmail(), $toUser->getName());
     $mail->setSubject($msgSubj);
     $mail->setBody($msgText);
     $transport = new Mail\Transport\Sendmail();
     //        $transport = new Mail\Transport\Smtp();
     //        $options   = new Mail\Transport\SmtpOptions(array(
     //            'name'              => 'smtp.gmail.com',
     //            'host'              => 'smtp.gmail.com',
     //            'connection_class'  => 'login',
     //            'connection_config' => array(
     //                'ssl'      => 'tls',
     //                'username' => '*****@*****.**',
     //                'password' => '',
     //            ),
     //        ));
     //        $transport->setOptions($options);
     $transport->send($mail);
     return true;
 }
Exemple #3
0
 public function send(SmtpTransport $transport = null, Message $message, array $attachments = array())
 {
     if ($transport == null) {
         $transport = new Sendmail();
     }
     $content = $message->getBody();
     $parts = $attachments;
     $parts = array();
     $bodyMessage = new \Zend\Mime\Message();
     $multiPartContentMessage = new \Zend\Mime\Message();
     $text = new Part(html_entity_decode(strip_tags(str_replace("<br />", "\n", $content))));
     $text->type = "text/plain";
     $text->encoding = Mime::ENCODING_QUOTEDPRINTABLE;
     $text->charset = 'UTF-8';
     $multiPartContentMessage->addPart($text);
     $html = new Part($content);
     $html->type = Mime::TYPE_HTML;
     $html->encoding = Mime::ENCODING_QUOTEDPRINTABLE;
     $html->charset = 'utf-8';
     $multiPartContentMessage->addPart($html);
     $multiPartContentMimePart = new Part($multiPartContentMessage->generateMessage());
     $multiPartContentMimePart->type = 'multipart/alternative;' . PHP_EOL . ' boundary="' . $multiPartContentMessage->getMime()->boundary() . '"';
     $bodyMessage->addPart($multiPartContentMimePart);
     foreach ($attachments as $attachment) {
         $bodyMessage->addPart($attachment);
     }
     $message->setBody($bodyMessage);
     $message->setEncoding("UTF-8");
     $transport->send($message);
 }
 protected function sendEmailAction()
 {
     $userTable = $this->getServiceLocator()->get('UserTable');
     if (true) {
         //$this->request->isPost()) {
         $subject = 'subject';
         //$this->request->getPost()->get('subject');
         $body = 'body';
         //$this->request->getPost()->get('body');
         $fromUserId = 1;
         //$this->user->id;
         $toUserId = 2;
         //$this->request->getPost()->get('toUserId');
         $fromUser = $userTable->getUser($fromUserId);
         $toUser = $userTable->getUser($toUserId);
         $mail = new Mail\Message();
         $mail->setFrom($fromUser->email, $fromUser->name);
         $mail->addTo($toUser->email, $toUser->name);
         $mail->setSubject($subject);
         $mail->setBody($body);
         $transport = new Mail\Transport\Sendmail();
         $transport->send($mail);
     }
     return true;
 }
 public function addAction()
 {
     $form = new BookForm();
     $form->get('submit')->setValue('Add');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $book = new Book();
         $form->setInputFilter($book->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $book->exchangeArray($form->getData());
             $this->getBookTable()->saveBook($book);
             //send email
             $mail = new Mail\Message();
             $mail->setBody('A new book called ' . $book->title . ' has been added.');
             $mail->setFrom('*****@*****.**', 'Zend Course');
             $mail->addTo('*****@*****.**', 'Myself');
             $mail->setSubject('A Book was added');
             $transport = new Mail\Transport\Sendmail();
             $transport->send($mail);
         }
         //Redirect to books list
         return $this->redirect()->toRoute('book');
     }
     return array('form' => $form);
 }
 /**
  * Add Action
  * <br/> Responsible for :
  *       <br/>In case Get verb  -> Display Add new Book Form
  *       <br/>In case Post verb -> Add new book details into Database
  *                                 After Submit Book Form
  * @return ViewModel add view
  */
 public function addAction()
 {
     $form = new BookForm();
     $form->get('submit')->setValue('Add');
     // Another way to set Submit button value
     // $form->get('submit')->setAttribute('value', 'Add');
     $request = $this->getRequest();
     // Check If request is Post verb
     if ($request->isPost()) {
         $book = new Book();
         $form->setInputFilter($book->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $book->exchangeArray($form->getData());
             $this->getBookTable()->saveBook($book);
             //Send an email when a new book Was Added
             $mail = new Mail\Message();
             $mail->setBody('A new Book called ' . $book->title . ' has been added.');
             $mail->setFrom('*****@*****.**', 'Zend course');
             $mail->addTo('*****@*****.**', 'Ahmed Hamdy');
             $mail->setSubject('A Book was Added');
             $transport = new Mail\Transport\Sendmail();
             $transport->send($mail);
         }
         // redirect to list of books
         return $this->redirect()->toRoute('book');
     }
     return new ViewModel(array('form' => $form));
 }
 /**
  * Sends the contact message via email
  *
  * @param array $data
  * @return boolean
  **/
 public function send($data)
 {
     $form = $this->getForm();
     $form->setData($data);
     if ($form->isValid()) {
         $data = $form->getData();
         $message = 'Name: ' . $data['name'] . "\r\n";
         $message .= 'Email: ' . $data['email'] . "\r\n\r\n";
         $message .= $data['comment'];
         $mail = new Message();
         $mail->setBody($message);
         $mail->setFrom('*****@*****.**');
         $mail->addTo('*****@*****.**', 'Rob Keplin');
         $mail->setSubject('From robkeplin.com');
         $transport = new Sendmail();
         try {
             $transport->send($mail);
         } catch (RuntimeException $e) {
             $this->addMessage('The email did not get sent due to sendmail failing. Doh!', self::MSG_ERROR);
             return false;
         }
         $form->setData(array('name' => '', 'email' => '', 'comment' => ''));
         $this->addMessage('Thanks.  Get back to you soon!', self::MSG_NOTICE);
         return true;
     }
     $this->addMessage('Hey, Wait! Something went wrong down there.  Please fix the errors and try again.', self::MSG_ERROR);
     return false;
 }
 public function sendCareerMail($sender, $recipient, $subject, $text, $filepath, $candidateName)
 {
     $result = false;
     try {
         //add attachment
         $text = new Mime\Part($text);
         $text->type = Mime\Mime::TYPE_TEXT;
         $text->charset = 'utf-8';
         $fileContent = fopen($filepath, 'r');
         $attachment = new Mime\Part($fileContent);
         $attachment->type = 'application/pdf';
         $attachment->filename = $candidateName;
         $attachment->disposition = Mime\Mime::DISPOSITION_ATTACHMENT;
         // Setting the encoding is recommended for binary data
         $attachment->encoding = Mime\Mime::ENCODING_BASE64;
         // then add them to a MIME message
         $mimeMessage = new Mime\Message();
         $mimeMessage->setParts(array($text, $attachment));
         // and finally we create the actual email
         $message = new Message();
         $message->setBody($mimeMessage);
         $message->setFrom($sender);
         $message->addTo($recipient);
         $message->setSubject($subject);
         // Send E-mail message
         $transport = new Sendmail('-f' . $sender);
         $transport->send($message);
         $result = true;
     } catch (\Exception $e) {
         $result = false;
     }
     // Return status
     return $result;
 }
 /**
  * Send email to contacts, insert message into db, log operation
  */
 public function sendAction()
 {
     $form = new ContactsForm();
     $request = $this->getRequest();
     if ($request->isPost()) {
         $mainLayout = $this->initializeFrontendWebsite();
         $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
         $inputFilter = new ContactsFormInputFilter();
         $form->setInputFilter($inputFilter->getInputFilter());
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $inputFilter->exchangeArray($form->getData());
             $formData = $request->getPost();
             $configurations = $this->layout()->getVariable('configurations');
             $mail = new Mail\Message();
             $mail->setFrom($configurations['emailnoreply'], $formData->nome . ' ' . $formData->cognome);
             $mail->addTo($configurations['emailcontact'], $configurations['sitename']);
             $mail->setSubject('Nuovo messaggio dal sito ' . $configurations['sitename']);
             $mail->setBody("Nome e cognome: \n " . $formData->nome . " " . $formData->cognome . " Email: " . $formData->email . "\n Messaggio: " . $formData->messaggio);
             $transport = new Mail\Transport\Sendmail();
             $transport->send($mail);
             $helper = new ContactsControllerHelper();
             $helper->setConnection($em->getConnection());
             $helper->insert($inputFilter);
             $this->layout()->setVariables(array('configuraitions' => $configurations, 'homepage' => !empty($homePageElements) ? $homePageElements : null, 'templatePartial' => 'contatti/ok.phtml'));
             $this->layout()->setTemplate($mainLayout);
         } else {
             foreach ($form->getInputFilter()->getInvalidInput() as $invalidInput) {
                 var_dump($form->getMessages());
             }
             exit;
         }
     }
 }
Exemple #10
0
 /**
  * Send the constructed email
  *
  * @todo Add from name
  */
 public function send($email)
 {
     $message = $this->prepare($email);
     //Send email
     if ($message && $this->config["active"]) {
         $transport = new SendmailTransport();
         return $transport->send($message);
     }
 }
Exemple #11
0
 /**
  * Send mail
  */
 public function sendMail()
 {
     if (!$this->transport) {
         $this->transport = new Sendmail();
     }
     $this->getMailMessageObject()->setFrom($this->emailFrom);
     $this->getMailMessageObject()->setSubject($this->emailFrom);
     $this->getMailMessageObject()->setBody($this->emailFrom);
     $this->transport->send($this->getMailMessageObject());
 }
 /**
  * Dispara um e-mail conforme as configurações fornecidas.
  *
  * @param string $name    Nome do remetente
  * @param string $email   E-mail do remetente
  * @param string $subject Assunto do e-mail
  * @param string $message Conteúdo a ser enviado
  */
 public function sendEmail($name, $email, $subject, $message)
 {
     $mail = new Mail\Message();
     $mail->addTo($email, $name);
     $mail->setFrom('*****@*****.**', 'MPRecruiter');
     $mail->setSubject($subject);
     $mail->setBody($message);
     $transport = new Mail\Transport\Sendmail();
     $transport->send($mail);
 }
 /**
  * Search POSTED user email, send email with request to regenerate password or choose a new one
  *
  * @return mixed
  */
 public function sendrecoverrequestAction()
 {
     /**
      * @var \Doctrine\ORM\EntityManager $em
      */
     $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
     $request = $this->getRequest();
     if (!$request->isPost()) {
         return $this->redirect()->toRoute('main');
     }
     $post = $request->getPost()->toArray();
     $inputFilter = new RecoverPasswordFormInputFilter();
     $form = new RecoverPasswordForm();
     $form->setInputFilter($inputFilter->getInputFilter());
     $form->setData($post);
     $helper = new UsersControllerHelper();
     $helper->setConnection($em->getConnection());
     if ($form->isValid()) {
         $userRecords = $helper->recoverWrapperRecords(new UsersGetterWrapper(new UsersGetter($em)), array('emailUsername' => $post['email'], 'limit' => 1));
         if (!empty($userRecords) and count($userRecords) == 1) {
             $confirmCode = md5(uniqid());
             $helper->updateConfirmCode($userRecords[0]['id'], $confirmCode);
             $uri = $request->getUri();
             $basePath = sprintf('%s://%s%s', $uri->getScheme(), $uri->getHost(), '');
             $linkRecoverPasswordForm = $basePath . $this->url()->fromRoute('recover-password', array('action' => 'formchangepassword', 'confirmcode' => $confirmCode));
             $appServiceLoader = $this->recoverAppServiceLoader(1);
             $configurations = $appServiceLoader->recoverService('configurations');
             $noReplayMail = isset($configurations['mailnoreply']) ? $configurations['mailnoreply'] : '*****@*****.**';
             $message = $configurations['sitename'] . "\n\n";
             $message .= "E' stata registrata una richiesta di recupero password per il sito in oggetto.\n\n";
             $message .= 'Per scegliere una nuova password, <a href="' . $linkRecoverPasswordForm . '">clicca qui</a>' . "\n\n";
             $message .= "Se non vedi il link, conferma la richiesta copiando e incollando il link sotto riportato sul tuo browser:\n\n";
             $message .= $linkRecoverPasswordForm . "\n\n";
             $message .= 'Non rispondere a questo messaggio' . "\n\n";
             $message .= date("Y") . ' ' . $configurations['sitename'];
             /* Send email with link for password recover */
             $mail = new Mail\Message();
             $mail->setBody($message);
             $mail->setFrom($noReplayMail, $configurations['sitename']);
             $mail->addTo($userRecords[0]['email'], $userRecords[0]['name'] . ' ' . $userRecords[0]['surname']);
             $mail->setSubject('Richiesta recupero password ', $configurations['sitename']);
             $transport = new Mail\Transport\Sendmail($userRecords[0]['email']);
             $transport->send($mail);
             /* Redirect to another page with OK message to avoid double POSTs */
             return $this->redirect()->toRoute('recover-password', array('action' => 'showconfirm', 'confirmcode' => 'passwordRequestSentOk'));
         } else {
             // User not found, invalid request...
         }
     } else {
         // The form is not valid, it can redirect to a confirm message page
     }
     return $this->redirect()->toRoute('main');
 }
 protected function sendOfflineMessage($msgSubj, $msgText, $fromUserId, $toUserId)
 {
     $userTable = $this->getServiceLocator()->get('UserTable');
     $fromUser = $userTable->getUser($fromUserId);
     $toUser = $userTable->getUser($toUserId);
     $mail = new Mail\Message();
     $mail->setFrom($fromUser->email, $fromUser->name);
     $mail->addTo($toUser->email, $toUser->name);
     $mail->setSubject($msgSubj);
     $mail->setBody($msgText);
     $transport = new Mail\Transport\Sendmail();
     $transport->send($mail);
     return true;
 }
 public function sendAction()
 {
     $form = new ContactForm();
     $request = $this->getRequest();
     if ($request->isPost()) {
         $data = $request->getPost();
         $message = new \Zend\Mail\Message();
         $message->setBody($data['body']);
         $message->setFrom($data['email']);
         $message->addTo('*****@*****.**');
         $message->setSubject($data['subject']);
         $transport = new SendmailTransport();
         $transport->send($message);
     }
     return ['form' => $form];
 }
 public function run()
 {
     $config = Config::get('xmailer.imap');
     $mail = new StorageImap(array('host' => $config['host'], 'user' => $config['user'], 'password' => $config['password']));
     //$mail = new StorageImap(Config::get('xmailer.imap'));
     if ($mail->countMessages() > 0) {
         $message = $mail->getMessage(1);
         if ($message->getHeaders()->get("from") != null) {
             $from = $message->getHeaders()->get("from")->toString();
         } else {
             $from = "";
         }
         if ($message->getHeaders()->get("to") != null) {
             $to = $message->getHeaders()->get("to")->toString();
         } else {
             $to = "";
         }
         preg_match("/[\\w._%+-]+@[\\w.-]+.[\\w]{2,}/", $from, $fromEmails);
         preg_match("/[\\w._%+-]+@[\\w.-]+.[\\w]{2,}/", $to, $toEmails);
         $sendTo = $this->getEmailAdresses($toEmails);
         if ($this->isValidSender($fromEmails[0])) {
             foreach ($sendTo as $mailadress) {
                 $fwd = new Message();
                 $fwd->setBody($message->getContent());
                 $h = $message->getHeaders();
                 $h->removeHeader('From');
                 $h->removeHeader('To');
                 $h->removeHeader('Reply-To');
                 $fwd->setHeaders($h);
                 $fwd->addFrom($mailadress['from']);
                 $fwd->addTo($mailadress['to']);
                 if (Config::get('xmailer.replyto')) {
                     $fwd->addReplyTo($fromEmails[0]);
                 }
                 $transport = new SendmailTransport();
                 $transport->send($fwd);
             }
             $mail->moveMessage(1, "INBOX.Sent");
         } else {
             $mail->moveMessage(1, "INBOX.Spam");
         }
         return t("%d email sent to %d People.", 1, count($sendTo));
     }
     return t("No emails sent.");
 }
 /**
  * Saves a comment and sends an email
  *
  * @param array $data
  * @return boolean
  **/
 public function save($data = array())
 {
     $data['comment'] = nl2br($data['comment']);
     $this->form->setData($data);
     if ($this->form->isValid()) {
         $comment = $this->form->getData();
         $comment->setDateAdded(new DateTime());
         $comment->setPost($this->post);
         $comment->setStatus(1);
         $comment->setIpAddress($_SERVER['REMOTE_ADDR']);
         //For display purposes
         if ($comment->getParentId()) {
             foreach ($this->post->getComments() as $oldComment) {
                 if ($oldComment->getId() == $comment->getParentId()) {
                     if ($oldComment->getParentId()) {
                         $comment->setParentId($oldComment->getParentId());
                     }
                     break;
                 }
             }
         }
         $this->em->persist($comment);
         $this->em->flush();
         $this->post->addComment($comment);
         $this->form->setData(array('name' => null, 'website' => null, 'email' => null, 'comment' => null, 'parent' => array('id' => 0)));
         $message = strip_tags($comment->getComment()) . "\r\n\r\n";
         $message .= $comment->getEmail() . "\r\n\r\n";
         $message .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
         $mail = new Message();
         $mail->setBody($message);
         $mail->setFrom('*****@*****.**');
         $mail->addTo('*****@*****.**', 'Rob Keplin');
         $mail->setSubject('New comment on robkeplin.com');
         $transport = new Sendmail();
         try {
             $transport->send($mail);
         } catch (RuntimeException $e) {
             $this->addMessage('A notification email was not sent due to sendmail failing. Doh!', self::MSG_ERROR);
         }
         $this->addMessage('Thanks for commenting.', self::MSG_NOTICE);
         return true;
     }
     $this->addMessage('Hey, Wait!  Something went wrong down there.  Please try commenting again, it did not go through.', self::MSG_ERROR);
     return false;
 }
 public function enviar()
 {
     $body = $this->assunto;
     $htmlPart = new MimePart($body);
     $htmlPart->type = "text/html";
     $textPart = new MimePart($body);
     $textPart->type = "text/plain";
     $body = new MimeMessage();
     $body->setParts(array($textPart, $htmlPart));
     $message = new Mail\Message();
     $message->setFrom($this->rementente);
     $message->addTo($this->destinatario);
     $message->setSubject($this->titulo);
     $message->setEncoding("UTF-8");
     $message->setBody($body);
     $message->getHeaders()->get('content-type')->setType('multipart/alternative');
     $transport = new Mail\Transport\Sendmail();
     $transport->send($message);
 }
 public function notificarAction()
 {
     //Conectamos a BBDD
     $sid = new Container('base');
     $db_name = $sid->offsetGet('dbNombre');
     $remitente = "Comit�";
     $this->dbAdapter = $this->getServiceLocator()->get($db_name);
     //Obtenemos datos POST
     $post = $this->request->getPost();
     if (isset($post['destino'])) {
         //Validamos si es mensaje directo a Dpto
         if (isset($post['dpto'])) {
             //Consultamos datos del dpto
             $dptoMail = new UnidadTable($this->dbAdapter);
             $lista = $dptoMail->getVerResidentesActivos($this->dbAdapter, $post['id_unidad']);
             $htmlMarkup = \HtmlCorreo::htmlMensajeDirecto($lista[0]['nombre'], $remitente, $post['textbody']);
             $html = new MimePart($htmlMarkup);
             $html->type = "text/html";
             $body = new MimeMessage();
             $body->setParts(array($html));
             $message = new Message();
             $message->addTo($lista[0]['correo'])->addFrom('*****@*****.**', 'Notificacion becheck')->setSubject($post['asunto'])->setBody($body);
             $transport = new SendmailTransport();
             $transport->send($message);
             //Retornamos a la vista
             $result = new JsonModel(array('status' => 'ok', 'descripcion' => 'Se ha enviado correctamente un correo'));
             //$result->setTerminal(true);
             return $result;
         }
         $result = new JsonModel(array('status' => 'ok', 'descripcion' => $post));
         $result->setTerminal(true);
         return $result;
     }
     //Instancias
     $dpto = new UnidadTable($this->dbAdapter);
     $form = new NotificacionForm("form");
     //Obtenemos combo dptos
     $dptos = $dpto->getDatosActivos();
     //Cargamos dptos en formulario
     $form->get('id_unidad')->setAttribute('options', $dptos);
     $this->layout('layout/comite');
     return new ViewModel(array('form' => $form));
 }
Exemple #20
0
 /**
  * Sends the mail message.
  * @param type $recipient
  * @param type $subject
  * @param type $text
  * @return boolean
  */
 public function sendMail($sender, $recipient, $subject, $text)
 {
     $result = false;
     try {
         // Create E-mail message
         $mail = new Mail\Message();
         $mail->setBody($text);
         $mail->setFrom($sender);
         $mail->addTo($recipient);
         $mail->setSubject($subject);
         // Send E-mail message
         $transport = new Mail\Transport\Sendmail('-f' . $sender);
         $transport->send($mail);
         $result = true;
     } catch (\Exception $e) {
         $result = false;
     }
     return $result;
 }
Exemple #21
0
 public function contactAction()
 {
     $entityManager = $this->getServiceLocator()->get('entity-manager');
     $superAdmin = $entityManager->getRepository(get_class(new User()))->findOneByRole(User::USER_SUPER_ADMIN);
     $request = $this->getRequest();
     $publicHtml = $this->getServiceLocator()->get('config')['public-path'];
     $form = new Contact($request->getBaseUrl() . '/core/img/captcha/', $publicHtml);
     if ($request->isPost()) {
         $form->setData($request->getPost());
         if ($form->isValid()) {
             $message = new Mail\Message();
             $message->setFrom($form->get('email')->getValue())->setTo($superAdmin->getEmail())->setSubject('Website Inquiry')->setBody($form->get('inquiry')->getValue());
             $transport = new Mail\Transport\Sendmail();
             $transport->send($message);
             $this->flashMessenger()->addSuccessMessage("The message has been successfully sent. We'll review it and will answer shortly");
             $this->redir()->toRoute('home/default', array('controller' => 'customPage', 'action' => 'contact'));
         }
     }
     return array('formActive' => $superAdmin->getEmail() ? true : false, 'contact_form' => $form);
 }
Exemple #22
0
    public function send($name, $email, array $values = array())
    {
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // no valid email provided
            return;
        }
        $sql = <<<SQL
SELECT
\t`mail`.`from`,
\t`mail`.`subject`,
\t`mail`.`text`,
\t`mail`.`html`,
\t`mail`.`values`
FROM 
\t{$this->registry['table.mail']} `mail`
WHERE 
\t`mail`.`name` = ?
SQL;
        $row = $this->sql->getRow($sql, array($name));
        if (!empty($row)) {
            // check values
            $neededValues = array();
            if (!empty($row['values'])) {
                $neededValues = explode(';', $row['values']);
            }
            $missingValues = array_diff($neededValues, array_keys($values));
            if (count($missingValues) > 0) {
                throw new Exception('Missing values "' . implode(', ', $missingValues) . '"" in ' . $name);
            }
            // send mail
            $mail = new Mail\Message();
            $mail->setBody($this->substituteVars($row['text'], $values));
            $mail->setFrom($row['from']);
            $mail->addTo($email);
            $mail->setSubject($this->substituteVars($row['subject'], $values));
            $transport = new Mail\Transport\Sendmail();
            $transport->send($mail);
        } else {
            throw new Exception('Invalid mail template');
        }
    }
 /**
  * Convenience method to send the emails
  *
  * @param string $toAddress 
  * @param string $toName 
  * @param string $subject 
  * @param string $body 
  * @return void
  */
 protected static function send($toAddress, $toName, $subject, $templateName, $templateVars = array())
 {
     $view = new PhpRenderer();
     $view->setResolver(self::initResolver());
     $viewModel = new ViewModel();
     $viewModel->setTemplate($templateName)->setVariables($templateVars);
     $content = $view->render($viewModel);
     $viewLayout = new ViewModel();
     $viewLayout->setTemplate('MailLayout')->setVariables(array('content' => $content));
     $html = new MimePart($view->render($viewLayout));
     $html->type = "text/html";
     $body = new MimeMessage();
     $body->setParts(array($html));
     $mail = new Message();
     $mail->setBody($body);
     $mail->setFrom('*****@*****.**', 'My social network');
     $mail->addTo($toAddress, $toName);
     $mail->setSubject($subject);
     $transport = new Sendmail();
     $transport->send($mail);
 }
Exemple #24
0
 public function nuevoAction()
 {
     $this->dbAdapter = $this->getServiceLocator()->get('Zend\\Db\\Adapter');
     $email = $this->request->getPost('email');
     $password = $this->request->getPost('password');
     $repeatPassword = $this->request->getPost('repeatPassword');
     $usuarios = $this->dbAdapter->query("SELECT * FROM usuario where email='{$email}' limit 1", Adapter::QUERY_MODE_EXECUTE);
     foreach ($usuarios as $user) {
         $email_exist = $user['email'];
     }
     if (!@ereg("^[a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9\\-]+\\.[a-zA-Z0-9\\-\\.]", $email)) {
         $mensaje = 'Tu correo electrónico es inválido.';
         $status = 0;
     } elseif ($password != $repeatPassword || strlen($password) < 5) {
         $mensaje = 'Tu contraseña no coincide o es muy corta';
         $status = 0;
     } elseif (@$email_exist == $email) {
         $mensaje = 'La cuenta de correo ya existe';
         $status = 0;
     } else {
         $add = new Usuario($this->dbAdapter);
         $string = Rand::getString(32, 'abcdefghijklmnopqrstuvwxyz', true);
         $datos = array('email' => $email, 'contrasena' => $password, 'verificado' => 'no', 'cod' => $string);
         $add->addUser($datos);
         $usuario = $add->getUserEmail($email);
         $mail = new Mail\Message();
         $base = base64_encode($email);
         $mail->setBody('¡Gracias por registrarte!. Para gozar de todos los beneficios es necesario que valides tu cuenta de correo electrónico en el siguiente enlace <a href="' . $this->getRequest()->getBaseUrl() . '/usuario/validar/' . $usuario[0]['id_usuario'] . '/' . $usuario[0]['cod'] . '">Validar Cuenta</a><br><br><img src="' . $this->getRequest()->getBaseUrl() . '/img/empresasveracruz2.png">');
         $mail->setFrom('*****@*****.**', 'Directorio EmpresasVeracruz');
         $mail->addTo($email);
         $mail->setSubject('Bienvenido a EmpresasVeracruz');
         $transport = new Mail\Transport\Sendmail();
         $transport->send($mail);
         $mensaje = "Registrado, por favor revisa tu bandeja de entrada para validar tu cuenta.";
         $status = 200;
     }
     $vista = new ViewModel(array('mensaje' => $mensaje, 'status' => $status));
     $this->layout('layout/ajax');
     return $vista;
 }
Exemple #25
0
 public function nuevoAction()
 {
     $this->dbAdapter = $this->getServiceLocator()->get('Zend\\Db\\Adapter');
     $email = $this->request->getPost('email');
     $password = $this->request->getPost('password');
     $repeatPassword = $this->request->getPost('repeatPassword');
     $usuarios = $this->dbAdapter->query("SELECT * FROM usuario where email='{$email}' limit 1", Adapter::QUERY_MODE_EXECUTE);
     foreach ($usuarios as $user) {
         $email_exist = $user['email'];
     }
     if (!@ereg("^[a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9\\-]+\\.[a-zA-Z0-9\\-\\.]", $email)) {
         $mensaje = 'Tu correo electrónico es inválido.';
         $status = 0;
     } elseif ($password != $repeatPassword || strlen($password) < 5) {
         $mensaje = 'Tu contraseña no coincide o es muy corta';
         $status = 0;
     } elseif (@$email_exist == $email) {
         $mensaje = 'La cuenta de correo ya existe';
         $status = 0;
     } else {
         $add = new Usuario($this->dbAdapter);
         $datos = array('email' => $email, 'contrasena' => $password, 'verificado' => 'no');
         $add->addUser($datos);
         $usuario = $add->getUserEmail($email);
         $mail = new Mail\Message();
         $base = base64_encode($email);
         $mail->setBody('This is the text of the email. <a href="http://www.empresasveracruz.com.mx/usuario/usuario/validar#' . $base . '">Validar Cuenta</a>');
         $mail->setFrom('*****@*****.**', 'Directorio EmpresasVeracruz');
         $mail->addTo($email);
         $mail->setSubject('Bienvenido a EmpresasVeracruz');
         $transport = new Mail\Transport\Sendmail();
         $transport->send($mail);
         $mensaje = "Registrado, por favor revisa tu bandeja de entrada para validar tu cuenta." . "<a href='http://www.empresasveracruz.com.mx/usuario/usuario/validar#" . $base . "'>Validar Cuenta</a>";
         $status = 200;
     }
     $vista = new ViewModel(array('mensaje' => $mensaje, 'status' => $status));
     $this->layout('layout/ajax');
     return $vista;
 }
 public function contatoAction()
 {
     if ($this->getRequest()->isPost()) {
         try {
             $mail = new Mail\Message();
             $mail->setBody($this->getRequest()->getPost()->get('message'));
             $mail->setFrom($this->getRequest()->getPost()->get('from'), $this->getRequest()->getPost()->get('nome'));
             $mail->addTo('*****@*****.**');
             $mail->setSubject('Mensagem pelo site');
             $transport = new Mail\Transport\Sendmail();
             $transport->send($mail);
             $message = 'Mensagem enviada com sucesso';
             $sucess = true;
         } catch (\Exception $e) {
             $message = 'Problema encontrado, tente mais tarde';
             $sucess = false;
         }
         return new JsonModel(['message' => $message, 'success' => $sucess]);
     } else {
         return new ViewModel();
     }
 }
Exemple #27
0
 public static function sendMailAttachment($data, $fileName, $subject, $receiveEmail, $smtp = true)
 {
     // setup SMTP options
     $config = Utility::getConfig();
     $options = new Mail\Transport\SmtpOptions(array('name' => 'localhost', 'host' => 'smtp.gmail.com', 'port' => 587, 'connection_class' => 'login', 'connection_config' => array('username' => $config['emailId'], 'password' => $config['emailPassword'], 'ssl' => 'tls')));
     if ($smtp) {
         $senderEmail = $config['emailId'];
         $senderName = $config['emailId'];
     } else {
         $senderEmail = $config['emailId'];
         $senderName = 'Kaffa - Coffee & more';
     }
     //        $render = self::$servicelocator->get('ViewRenderer');
     //$content = $render->render('email/' . $templateName, array('data' => $data));
     $content = fopen($data, 'r');
     // make a header as html
     $html = new MimePart($content);
     $html->type = \Zend\Mime\Mime::TYPE_OCTETSTREAM;
     $html->filename = $fileName;
     $html->disposition = \Zend\Mime\Mime::DISPOSITION_INLINE;
     $body = new MimeMessage();
     $body->setParts(array($html));
     // instance mail
     $mail = new Mail\Message();
     $mail->setBody($body);
     // will generate our code html from template.phtml
     $mail->setFrom($senderEmail, $senderName);
     $mail->setTo($receiveEmail);
     $mail->setSubject($subject);
     if ($smtp) {
         $transport = new Mail\Transport\Smtp($options);
     } else {
         $transport = new Mail\Transport\Sendmail();
     }
     $transport->send($mail);
 }
Exemple #28
0
 public function sendMailToBuyers(array $params)
 {
     if (!empty($params['allusers'])) {
         // get all users to email
         $select = new Select('buyers');
         $select->columns(array('user_id', 'email', 'name'));
         $string = $this->sql->buildSqlString($select);
         $adapter = $this->table_gateway->getAdapter();
         $rowset = $adapter->query($string, $adapter::QUERY_MODE_EXECUTE);
         $holder = array();
         foreach ($rowset as $rows) {
             $temp = array();
             $user_id = $rows->user_id;
             $temp['email'] = $rows->email;
             $temp['name'] = $rows->name;
             $users[] = $temp;
         }
     } else {
         if (!empty($params['rightValues'])) {
             for ($i = 0; $i < count($params['rightValues']); $i++) {
                 $str = explode("::", $params['rightValues'][$i]);
                 $temp = array();
                 $temp['email'] = $str[0];
                 $temp['name'] = $str[2];
                 $users[] = $temp;
             }
         }
     }
     // send the emails now
     $tpl_table = new Select('email_templates');
     $tpl_table->columns(array('template_id', 'template_title', 'email_subject', 'email_body'))->where('template_id = 21');
     $string = $this->sql->buildSqlString($tpl_table);
     $adapter = $this->table_gateway->getAdapter();
     $rowset = $adapter->query($string, $adapter::QUERY_MODE_EXECUTE);
     if (count($rowset) > 0) {
         $holder = array();
         foreach ($rowset as $rows) {
             $holder = $rows;
         }
         $msg_text = $holder->email_body;
         $subject = $holder->email_subject;
         $msg_text = str_replace("[SITENAME]", "my site", $msg_text);
         $msg_text = str_replace("[SITEURL]", "http://" . $_SERVER['SERVER_NAME'] . "/", $msg_text);
         foreach ($users as $user) {
             if (!empty($user['name'])) {
                 $message = str_replace("[NAME]", $user['name'], $msg_text);
             } else {
                 $message = str_replace("[NAME]", $user['email'], $msg_text);
             }
             // make the content html and not text
             $mime = new Mime\Part($message);
             $mime->type = "text/html";
             $mime_msg = new Mime\Message();
             $mime_msg->setParts(array($mime));
             $mail = new Mail\Message();
             $mail->addFrom($message)->addTo($user['email'])->setSubject($holder->subject)->setBody($mime_msg);
             // send the email now
             $send = new Mail\Transport\Sendmail();
             $send->send($mail);
         }
     }
 }
Exemple #29
0
 public function send()
 {
     $log = $this->getController()->getServiceLocator()->get('Log/Core/Mail');
     $this->getHeaders()->addHeaderLine('X-Mailer', 'php/YAWIK');
     //foreach (array('ASCII', 'UTF-8', 'ISO-8859-1', 'ISO-8859-15', 'ISO-8859-7') as $encoding) {
     $encoding = 'UTF-8';
     //$this->getHeaders()->addHeaderLine('charset', $encoding);
     $this->getHeaders()->addHeaderLine('Content-Type', 'text/plain; charset=UTF-8');
     //$this->getHeaders()->setEncoding($encoding);
     $transport = new Sendmail();
     $erg = False;
     try {
         $transport->send($this);
         $erg = True;
         $log->info($this);
     } catch (Exception $e) {
         $log->err('Mail failure ' . $e->getMessage());
         //$this->getController()->getServiceLocator()->get('Core/Log')->warn('Mail failure ' . $e->getMessage());
     }
     //}
     return $erg;
 }
Exemple #30
0
 public function lostPasswordAction()
 {
     $viewModel = new ViewModel();
     $form = new LostPasswordForm();
     $accountFilter = new AccountFIlter();
     $filter = new InputFilter();
     $filter->add($accountFilter->get('email'));
     $form->setInputFilter($filter);
     $request = $this->getRequest();
     if ($request->isPost()) {
         $data = $request->getPost();
         $form->setData($data);
         if ($form->isValid()) {
             $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
             // 找到使用者
             if ($user = $em->getRepository('Base\\Entity\\User')->findOneBy(array('email' => $form->get('email')->getValue()))) {
                 $md5 = md5(time() . $user->getUserName() . $user->getEmail());
                 $user->setCheckCode($md5);
                 $em->persist($user);
                 $em->flush();
                 $view = new \Zend\View\Renderer\PhpRenderer();
                 $resolver = new \Zend\View\Resolver\TemplateMapResolver();
                 $resolver->setMap(array('mailLayout' => __DIR__ . '/../../../../Application/view/layout/layout-mail.phtml', 'mailTemplate' => __DIR__ . '/../../../view/user/sign/lost-password-mail.phtml'));
                 $view->setResolver($resolver);
                 $uri = $this->getRequest()->getUri();
                 $scheme = $uri->getScheme();
                 $host = $uri->getHost();
                 $base = sprintf('%s://%s%s', $scheme, $host, $this->getRequest()->getBasePath());
                 $viewModel->setTemplate('mailTemplate')->setVariables(array('user' => $user, 'url' => $base));
                 $content = $view->render($viewModel);
                 $viewLayout = new ViewModel();
                 $viewLayout->setTemplate('mailLayout')->setVariables(array('content' => $content));
                 $body = $view->render($viewLayout);
                 $bodyPart = new \Zend\Mime\Message();
                 $bodyMessage = new \Zend\Mime\Part($body);
                 $bodyMessage->type = 'text/html';
                 $bodyPart->setParts(array($bodyMessage));
                 $message = new Mail\Message();
                 $message->addTo($user->getEmail(), $user->getusername());
                 $message->setFrom('*****@*****.**', '系統通知信');
                 $message->setSubject('重設密碼通知信');
                 $message->setBody($bodyPart);
                 $message->setEncoding('UTF-8');
                 $transport = new Mail\Transport\Sendmail();
                 $transport->send($message);
                 // $viewModel->setTemplate('user/login/send-mail.phtml');
                 $this->flashmessenger()->addMessage($user->getEmail());
                 return $this->redirect()->toRoute('user/default', array('controller' => 'sign', 'action' => 'send-mail'));
                 // return $viewModel;
             } else {
                 $this->flashmessenger()->addMessage('您輸入了錯誤的帳號或電子郵件');
             }
         }
     }
     $viewModel->setVariable('form', $form);
     $viewModel->setVariable('flashMessages', $this->flashMessenger()->getMessages());
     return $viewModel;
 }