/** * Factory method for creating an email log writer based on the configuration array * @param array $config * @return \Zend\Log\Writer\Mail */ public function create($config) { $to = $config['to']; $from = $config['from']; $subject = $config['subject']; //create the message object that should be sent $message = new \Zend\Mail\Message(); //populate it with data based on the config $message->setFrom($from); $message->setSubject($subject); if (is_string($to)) { $to = array($to); } foreach ($to as $email) { $message->addTo($email); } //create the log writer $writer = new Mail($message); //set up a formatter if present if (isset($config['formatter'])) { $formatter = new $config['formatter'](); $writer->setFormatter($formatter); } return $writer; }
/** * Realiza o envio do email * * @param $nome * @param $email * @param $assunto * @param $conteudo * * @return $this */ public function sendMail($nome, $email, $assunto, $conteudo) { $message = new \Zend\Mail\Message(); $htmlPart = new \Zend\Mime\Part($conteudo); $htmlPart->type = 'text/html'; $body = new MimeMessage(); $body->setParts(array($htmlPart)); $message->setFrom($this->emailSender, $this->nomeSender); $message->addTo($email, $nome); $message->setSubject($assunto); $message->setBody($body); $this->getTransport()->send($message); return $this; }
/** * Creates a new user * @param \Zend\Db\Adapter\Adapter $db * @param type $login * @param type $password * @return \login\user\User */ public static function createLoginInstance(\Zend\Db\Adapter\Adapter $db, $login, $password) { $user = self::getLoginInstance($db, $login); if (is_object($user) && $user->getData('username') != '') { throw new \Exception('Username already used ' . $login, 1409011238); } $adminColl = new \login\user\LoginColl($db); $adminColl->loadAll(array('role_id' => 3)); $role_id = 3; $role_description = 'User'; $active = 0; if ($adminColl->count() == 0) { $role_id = 1; $role_description = 'Administrator'; $active = 1; } $profileRole = new \login\user\ProfileRole($db); $profileRole->loadFromId($role_id); if ($profileRole->getData('id') != $role_id) { $defaultRuleFile = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'install' . DIRECTORY_SEPARATOR . 'sql' . DIRECTORY_SEPARATOR . 'profile_role.sql'; if (is_file($defaultRuleFile)) { $db->query(file_get_contents($defaultRuleFile), \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE); } $profileRole->loadFromId($role_id); if ($profileRole->getData('id') != $role_id) { $profileRole->setData(array('id' => $role_id, 'description' => $role_description)); $profileRole->insert(); } } $user = new \login\user\Login($db); $user->setData(array('username' => $login, 'password' => md5($password), 'creation_datetime' => date('Y-m-d H:i:s'), 'confirm_code' => md5(serialize($_SERVER) . time()))); $user->insert(); $profile = $user->getProfile(); $profile->setData(array('role_id' => $role_id, 'active' => $active)); $profile->update(); ob_start(); require $db->baseDir . DIRECTORY_SEPARATOR . 'mail' . DIRECTORY_SEPARATOR . 'register.php'; $html = new \Zend\Mime\Part(ob_get_clean()); $html->type = 'text/html'; $body = new \Zend\Mime\Message(); $body->setParts(array($html)); $message = new \Zend\Mail\Message(); $message->addTo($login)->addFrom($GLOBALS['config']->mail_from)->setSubject('Registrazione sul sito ' . $GLOBALS['config']->siteName)->setBody($body); $GLOBALS['transport']->send($message); if ($adminColl->count() > 0) { ob_start(); require $db->baseDir . DIRECTORY_SEPARATOR . 'mail' . DIRECTORY_SEPARATOR . 'new_user.php'; $html = new \Zend\Mime\Part(ob_get_clean()); $html->type = 'text/html'; $body = new \Zend\Mime\Message(); $body->setParts(array($html)); $message = new \Zend\Mail\Message(); foreach ($adminColl->getItems() as $admin) { $message->addTo($admin->getData('username')); } $message->addFrom($GLOBALS['config']->mail_from)->setSubject('Registrazione sul sito ' . $GLOBALS['config']->siteName)->setBody($body); $GLOBALS['transport']->send($message); } return $user; }
public function __invoke(MvcEvent $e) { if (file_exists('./logs/')) { $oWriterStream = new \Zend\Log\Writer\Stream('./logs/' . date('Y-m-d') . '-log.txt'); $oLogger = new \Zend\Log\Logger(); $oMessage = new \Zend\Mail\Message(); $oTransport = new \Zend\Mail\Transport\Sendmail(); $oMessage->setFrom('*****@*****.**', 'Łukasz Staszak'); $oMessage->addTo('*****@*****.**', 'Hello'); $oMail = new \Zend\Log\Writer\Mail($oMessage, $oTransport); $oMail->setSubjectPrependText('PHP Error'); $oLogger->addWriter($oWriterStream); $oLogger->addWriter($oMail); $oLogger->crit($e->getParam('exception')); } }
/** * Prepare header string from message * * @param Message $message * @return string */ protected function prepareHeaders(Zend\Mail\Message $message) { $originalSubject = ''; $headers = $message->getHeaders(); if ($headers->has('Subject')) { $subjectHeader = $headers->get('Subject'); $originalSubject = $subjectHeader->getFieldValue(); } $body = $message->getBody(); if ($body instanceof Zend\Mime\Message) { $parts = $body->getParts(); foreach ($parts as $part) { /* @var $part Zend\Mime\Part */ if ($part->getType() == Zend\Mime\Mime::TYPE_HTML) { $part->setContent("******** PGP/MIME-ENCRYPTED MESSAGE ********<br>\n" . "Subject: " . $originalSubject . "<br><br>\n" . $part->getContent()); } if ($part->getType() == Zend\Mime\Mime::TYPE_TEXT) { $part->setContent("******** PGP/MIME-ENCRYPTED MESSAGE ********\n" . "Subject: " . $originalSubject . "\n\n" . $part->getContent()); } } } else { $message->setBody("******** PGP/MIME-ENCRYPTED MESSAGE ********\n" . "Subject: " . $originalSubject . "\n\n" . $body); } $originalHeaders = parent::prepareHeaders($message); $originalBody = parent::prepareBody($message); $recipients = array(); foreach ($message->getTo() as $destination) { $recipients[] = $destination->getEmail(); } foreach ($message->getCc() as $destination) { $recipients[] = $destination->getEmail(); } foreach ($message->getBcc() as $destination) { $recipients[] = $destination->getEmail(); } global $openpgplib; $pgpmime_msg = $openpgplib->prepareEncryptWithZendMail($originalHeaders, $originalBody, $recipients); $headers = $pgpmime_msg[0]; // set pgp/mime headers from result array $this->OpenGPGStoreMailBody = $pgpmime_msg[1]; // set pgp/mime encrypted message body from result array return $headers; }
public function sendEmailsFromQueue($developmentMode = false) { $transport = $this->serviceManager->get('SlmMail\\Mail\\Transport\\SesTransport'); $entity = new $this->config['database']['entity'](); $tableName = $this->entityManager->getClassMetadata(get_class($entity))->getTableName(); $dql = 'SELECT m FROM ' . $this->config['database']['entity'] . ' m WHERE m.send = 0 AND m.scheduleDate <= :now ORDER BY m.prio, m.createDate DESC'; $query = $this->entityManager->createQuery($dql)->setParameter('now', date('Y-m-d H:i:s'))->setMaxResults($this->config['numberOfEmailsPerRun']); $queue = $query->getResult(); foreach ($queue as $mail) { // In development mode we only send emails to predefined email addresses to prevent "strange" unrequested // emails to users. if ($developmentMode === true && !in_array($mail->getRecipientEmail(), $this->config['developmentEmails'])) { $this->entityManager->getConnection()->update($tableName, array('send' => 1), array('id' => $mail->getId())); continue; } $message = new \Zend\Mail\Message(); $message->addFrom($mail->getSenderEmail(), $mail->getSenderName())->addTo($mail->getRecipientEmail(), $mail->getRecipientName())->setSubject($mail->getSubject()); if (trim($mail->getBodyHTML()) !== '') { $bodyPart = new \Zend\Mime\Message(); $bodyMessage = new \Zend\Mime\Part($mail->getBodyHTML()); $bodyMessage->type = 'text/html'; $bodyPart->setParts(array($bodyMessage)); $message->setBody($bodyPart); $message->setEncoding('UTF-8'); } else { $message->setBody($mail->getBodyText()); } try { $transport->send($message); $this->entityManager->getConnection()->update($tableName, array('send' => 1, 'sendDate' => date('Y-m-d H:i:s')), array('id' => $mail->getId())); } catch (\Exception $e) { $this->entityManager->getConnection()->update($tableName, array('send' => 2, 'error' => $e->getMessage()), array('id' => $mail->getId())); $this->queueNewMessage('MailAdmin', $this->config['adminEmail'], $e->getMessage(), $e->getMessage(), 'MailQueue Error', 9); } } }
public function index02Action() { $message = new \Zend\Mail\Message(); $message->setBody('This is the text of the email.'); $message->setFrom('*****@*****.**', 'Sender\'s name'); $message->addTo('*****@*****.**', 'Name of recipient'); $message->setSubject('TestSubject'); $transport = new \Zend\Mail\Transport\Sendmail(); $transport->send($message); }
private function sendMail($messageBody, $subject) { $message = new \Zend\Mail\Message(); $message->setEncoding('utf-8'); $message->setBody($messageBody); $message->addTo('*****@*****.**'); $message->setSubject($subject); $message->setFrom('*****@*****.**'); $transport = new \Zend\Mail\Transport\Sendmail(); if (APPLICATION_ENV == 'production') { $transport->send($message); } return true; }
public function send($params) { list($recipient, $sender, $issue) = $params; $mail = new \Zend\Mail\Message(); $mail->setBody($issue['rule']); $mail->setFrom('*****@*****.**', 'OnTheGo Notifier'); $mail->addTo($recipient); $mail->setSubject('Issue report on Zend Server'); $transport = new \Zend\Mail\Transport\Sendmail(); $transport->send($mail); }
protected function createMessage(array $data) { $message = new \Zend\Mail\Message(); $message->setBody($_POST['message']); $message->setFrom($_POST['email']); $message->setSubject(" contact message "); $message->addTo('*****@*****.**'); $smtpOptions = new \Zend\Mail\Transport\SmtpOptions(); $smtpOptions->setHost('smtp.gmail.com')->setConnectionClass('login')->setName('smtp.gmail.com')->setConnectionConfig(array('username' => '*****@*****.**', 'password' => 'Yatakafils1', 'ssl' => 'tls')); $transport = new \Zend\Mail\Transport\Smtp($smtpOptions); $transport->send($message); }
public function indexAction() { $message = new \Zend\Mail\Message(); $message->setBody('This is the body'); $message->setFrom('*****@*****.**'); $message->addTo('*****@*****.**'); $message->setSubject('Test subject'); $this->transport->send($message); return 'email'; die; $view = new ViewModel(); $view->setTemplate('auth/add'); return $view; }
public function message($error, $typestr) { $currentDate = new \DateTime('now'); $configEmail = $this->getConfigEmail(); $configSend = $configEmail['send']; $from = $configSend['from']; $subject = $configSend['subject']; $to = $configSend['to']; $message = new \Zend\Mail\Message(); $message->setFrom($from); foreach ($to as $emailTo) { $message->addTo($emailTo); } $message->setSubject($subject . ' - ' . $typestr); $errorMessage = "Host => " . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] . "\n" . "IP Request => " . $_SERVER['REMOTE_ADDR'] . "\n" . "Date => " . $currentDate->format('Y-m-d H:i') . "\n " . $error; $message->setBody($errorMessage); $message->setEncoding("UTF-8"); return $message; }
public function indexAction() { //return new ViewModel(); $contact_form = new ContactForm(); $request = $this->getRequest(); if ($request->isPost()) { $message = new \Zend\Mail\Message(); $message->setBody($_POST['message']); $message->setFrom($_POST['email_adress']); $message->setSubject(" contact message "); $message->addTo('*****@*****.**'); $smtpOptions = new \Zend\Mail\Transport\SmtpOptions(); $smtpOptions->setHost('smtp.gmail.com')->setConnectionClass('login')->setName('smtp.gmail.com')->setConnectionConfig(array('username' => '*****@*****.**', 'password' => '#############', 'ssl' => 'tls')); $transport = new \Zend\Mail\Transport\Smtp($smtpOptions); $transport->send($message); } return array('form' => $contact_form); }
/** * @see \BoilerAppMessenger\Message\MessageTransporterInterface::sendMessage() * @param \BoilerAppMessenger\Message\Message $oMessage * @throws \UnexpectedValueException * @return \BoilerAppMessenger\Media\Mail\MailMessageTransporter */ public function sendMessage(\BoilerAppMessenger\Message\Message $oMessage) { //Adapt message $oAdaptedMessage = new \Zend\Mail\Message(); $oAdaptedMessage->setEncoding('UTF-8'); //From Sender $oFrom = $oMessage->getFrom(); if ($oFrom instanceof \BoilerAppMessenger\Media\Mail\MailMessageUserInterface) { $oAdaptedMessage->setFrom($oFrom->getUserEmail(), $oFrom->getUserDisplayName()); } else { throw new \UnexpectedValueException(sprintf('"From" sender expects an instance of \\BoilerAppMessenger\\Mail\\MailMessageUserInterface, "%s" given', is_scalar($oFrom) ? $oFrom : (is_object($oFrom) ? get_class($oFrom) : gettype($oFrom)))); } //To Recipiants foreach ($oMessage->getTo() as $oTo) { if ($oTo instanceof \BoilerAppMessenger\Media\Mail\MailMessageUserInterface) { $oAdaptedMessage->addTo($oTo->getUserEmail(), $oTo->getUserDisplayName()); } else { throw new \UnexpectedValueException(sprintf('"To" Recipiant expects an instance of \\BoilerAppMessenger\\Mail\\MailMessageUserInterface, "%s" given', is_scalar($oTo) ? $oTo : (is_object($oTo) ? get_class($oTo) : gettype($oTo)))); } } //Subject $oAdaptedMessage->setSubject($oMessage->getSubject()); //Reset attachments $this->attachments = array(); foreach ($oMessage->getAttachments() as $sAttachmentFilePath) { $this->addFileAttachment($sAttachmentFilePath); } //Body $oBodyPart = new \Zend\Mime\Part(preg_replace_callback('/src="([^"]+)"/', array($this, 'processImageSrc'), $this->getMessageRenderer()->renderMessageBody($oMessage))); $oBodyPart->type = \Zend\Mime\Mime::TYPE_HTML; $oBody = new \Zend\Mime\Message(); $oBody->setParts(array_merge(array($oBodyPart), $this->attachments)); $oAdaptedMessage->setBody($oBody)->setEncoding('UTF-8'); //Send message $this->getMailTransporter()->send($oAdaptedMessage); return $this; }
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']); } if (count(array_diff(array_keys($values), $neededValues)) > 0) { throw new Exception('Missing values in ' . $name); } // send mail $mail = new \Zend\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 \Zend\Mail\Transport\Sendmail(); $transport->send($mail); } else { throw new Exception('Invalid mail template'); } }
public function backupAction() { $log = $this->getServiceLocator()->get('log'); $log->addInfo('备份数据' . "\t" . $this->getRequest()->getServer('REMOTE_ADDR') . "\t" . $this->getRequest()->getHeaders()->get('User-Agent')->getFieldValue()); $dbconf = $this->getServiceLocator()->get('config')['mysqli']; $dump = new \MySQLDump(new \mysqli($dbconf['host'], $dbconf['username'], $dbconf['password'], $dbconf['dbname'])); $filename = date("Y-m-d_H-i-s") . "-db.sql"; $tmpFile = dirname(__FILE__) . "\\" . $filename; $dump->save($tmpFile); $body = new Message(); $part = new Part(); $part->setType(Mime::TYPE_OCTETSTREAM); $part->setContent(file_get_contents($tmpFile)); $part->setDisposition(Mime::DISPOSITION_ATTACHMENT); $part->setFileName($filename); $part2 = new Part(); $part2->setType(Mime::TYPE_TEXT); $part2->setContent('小秋来发数据了'); $body->addPart($part); $body->addPart($part2); $newmessage = new \Zend\Mail\Message(); $newmessage->addTo($this->getServiceLocator()->get('MailOptions')->getMailTo()); $newmessage->addFrom($this->getServiceLocator()->get('MailOptions')->getMailFrom()); $newmessage->setBody($body); $newmessage->setSubject('备份数据'); $transport = new SmtpTransport(); $options = new SmtpOptions($this->getServiceLocator()->get('config')['mail']); $transport->setOptions($options); try { $transport->send($newmessage); echo 1; } catch (\Exception $e) { echo -1; } exit; }
/** * Send an event by email to the corresponding IPO */ public function sendEventAction() { $id = $this->params()->fromQuery('id', 0); $messages = array(); if ($id) { $objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager'); $eventservice = $this->getServiceLocator()->get('EventService'); $customfieldservice = $this->getServiceLocator()->get('CustomFieldService'); $event = $objectManager->getRepository('Application\\Entity\\Event')->find($id); $formatter = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN, 'dd LLL, HH:mm'); if ($event) { $content = 'Nom : ' . $eventservice->getName($event) . '<br />'; $content .= 'Début : ' . $formatter->format($event->getStartdate()) . '<br />'; $content .= 'Fin : ' . ($event->getEnddate() ? $formatter->format($event->getEnddate()) : 'Inconnu') . '<br />'; foreach ($event->getCustomFieldsValues() as $value) { $content .= $value->getCustomField()->getName() . ' : ' . $customfieldservice->getFormattedValue($value->getCustomField(), $value->getValue()) . '<br />'; } $text = new \Zend\Mime\Part($content); $text->type = \Zend\Mime\Mime::TYPE_HTML; $text->charset = 'utf-8'; $mimeMessage = new \Zend\Mime\Message(); $mimeMessage->setParts(array($text)); $config = $this->serviceLocator->get('config'); if (!$config['emailfrom'] || !$config['smtp']) { $messages['error'][] = "Envoi d'email non configuré, contactez votre administrateur."; } else { $message = new \Zend\Mail\Message(); $message->addTo($event->getOrganisation()->getIpoEmail())->addFrom($config['emailfrom'])->setSubject("Envoi d'un évènement par le CDS : " . $eventservice->getName($event))->setBody($mimeMessage); $transport = new \Zend\Mail\Transport\Smtp(); $transportOptions = new \Zend\Mail\Transport\SmtpOptions($config['smtp']); $transport->setOptions($transportOptions); try { $transport->send($message); $messages['success'][] = "Evènement correctement envoyé à " . $event->getOrganisation()->getIpoEmail(); } catch (\Exception $e) { $messages['error'][] = $e->getMessage(); } } } else { $messages['error'][] = "Envoi d'email impossible : évènement non trouvé."; } } else { $messages['error'][] = "Envoi d'email impossible : évènement non trouvé."; } $json = array(); $json['messages'] = $messages; return new JsonModel($json); }
protected function sendQueueItem(Entity $queueItem, Entity $massEmail, Entity $emailTemplate, $attachmetList = [], $campaign = null, $isTest = false) { $target = $this->getEntityManager()->getEntity($queueItem->get('targetType'), $queueItem->get('targetId')); if (!$target || !$target->id || !$target->get('emailAddress')) { $queueItem->set('status', 'Failed'); $this->getEntityManager()->saveEntity($queueItem); return; } $emailAddress = $target->get('emailAddress'); if (!$emailAddress) { $queueItem->set('status', 'Failed'); $this->getEntityManager()->saveEntity($queueItem); return false; } $emailAddressRecord = $this->getEntityManager()->getRepository('EmailAddress')->getByAddress($emailAddress); if ($emailAddressRecord) { if ($emailAddressRecord->get('invalid') || $emailAddressRecord->get('optOut')) { $queueItem->set('status', 'Failed'); $this->getEntityManager()->saveEntity($queueItem); return false; } } $trackingUrlList = []; if ($campaign) { $trackingUrlList = $campaign->get('trackingUrls'); } $email = $this->getPreparedEmail($queueItem, $massEmail, $emailTemplate, $target, $trackingUrlList); $params = array(); if ($massEmail->get('fromName')) { $params['fromName'] = $massEmail->get('fromName'); } if ($massEmail->get('replyToName')) { $params['replyToName'] = $massEmail->get('replyToName'); } try { $attemptCount = $queueItem->get('attemptCount'); $attemptCount++; $queueItem->set('attemptCount', $attemptCount); $message = new \Zend\Mail\Message(); $header = new \Espo\Core\Mail\Mail\Header\XQueueItemId(); $header->setId($queueItem->id); $message->getHeaders()->addHeader($header); $this->getMailSender()->useGlobal()->send($email, $params, $message, $attachmetList); $emailObject = $emailTemplate; if ($massEmail->get('storeSentEmails')) { $this->getEntityManager()->saveEntity($email); $emailObject = $email; } $queueItem->set('emailAddress', $target->get('emailAddress')); $queueItem->set('status', 'Sent'); $queueItem->set('sentAt', date('Y-m-d H:i:s')); $this->getEntityManager()->saveEntity($queueItem); if ($campaign) { $this->getCampaignService()->logSent($campaign->id, $queueItem->id, $target, $emailObject, $target->get('emailAddress')); } } catch (\Exception $e) { if ($queueItem->get('attemptCount') >= self::MAX_ATTEMPT_COUNT) { $queueItem->set('status', 'Failed'); } $this->getEntityManager()->saveEntity($queueItem); $GLOBALS['log']->error('MassEmail#sendQueueItem: [' . $e->getCode() . '] ' . $e->getMessage()); return false; } return true; }
return array('doctrine' => array('driver' => array('user_driver' => array('class' => 'Doctrine\\ORM\\Mapping\\Driver\\AnnotationDriver', 'paths' => array(__DIR__ . '/../src/User/Entity')), 'orm_default' => array('drivers' => array('User\\Entity' => 'user_driver'))), 'configuration' => array('orm_default' => array('types' => array('enumstatus' => 'User\\DBAL\\Types\\EnumStatusType'))), 'authentication' => array('orm_default' => array('object_manager' => 'Doctrine\\ORM\\EntityManager', 'identity_class' => 'User\\Entity\\Auth', 'identity_property' => 'foreignKey', 'credential_property' => 'token', 'credential_callable' => '\\User\\Service\\Auth::encrypt'))), 'router' => array('routes' => array('login' => array('type' => 'Literal', 'options' => array('route' => '/login', 'defaults' => array('__NAMESPACE__' => 'User\\Controller', 'controller' => 'Auth', 'action' => 'login')), 'may_terminate' => true), 'user' => array('type' => 'Literal', 'options' => array('route' => '/user', 'defaults' => array('__NAMESPACE__' => 'User\\Controller', 'controller' => 'index', 'action' => 'index')), 'may_terminate' => true, 'child_routes' => array('default' => array('type' => 'Segment', 'options' => array('route' => '/[:controller[/:action[/:id]]]', 'constraints' => array('controller' => '[a-zA-Z][a-zA-Z0-9_-]*', 'action' => '[a-zA-Z][a-zA-Z0-9_-]*'), 'defaults' => array())), 'confirm' => array('type' => 'Segment', 'options' => array('route' => '/signup/confirm/:confirm', 'defaults' => array('controller' => 'signup', 'action' => 'confirm'))), 'recover-password' => array('type' => 'Segment', 'options' => array('route' => '/auth/recover-password/:hash', 'defaults' => array('controller' => 'auth', 'action' => 'recover-password'))))))), 'controllers' => array('invokables' => array('User\\Controller\\Signup' => 'User\\Controller\\SignupController', 'User\\Controller\\Auth' => 'User\\Controller\\AuthController', 'User\\Controller\\Mail' => 'User\\Controller\\MailController', 'User\\Controller\\Management' => 'User\\Controller\\ManagementController', 'User\\Controller\\Profile' => 'User\\Controller\\ProfileController')), 'view_manager' => array('template_path_stack' => array(__DIR__ . '/../view'), 'template_map' => array('error/403' => __DIR__ . '/../view/error/403.phtml')), 'service_manager' => array('factories' => array('Db\\Adapter' => 'Zend\\Db\\Adapter\\AdapterServiceFactory', 'Zend\\Authentication\\AuthenticationService' => function ($serviceManager) { // If you are using DoctrineORMModule return $serviceManager->get('doctrine.authenticationservice.orm_default'); }, 'User\\Service\\User' => function ($sm) { return new User\Service\User($sm); }, 'User\\Service\\Auth' => function ($sm) { return new User\Service\Auth($sm); }, 'User\\Provider\\Identity\\DoctrineProvider' => function ($sm) { $entityManager = $sm->get('Doctrine\\ORM\\EntityManager'); $authService = $sm->get('Zend\\Authentication\\AuthenticationService'); $doctrineProvider = new User\Provider\Identity\DoctrineProvider($entityManager, $authService); $doctrineProvider->setServiceLocator($sm); $config = $sm->get('BjyAuthorize\\Config'); $doctrineProvider->setDefaultRole($config['default_role']); return $doctrineProvider; }, 'mail.transport' => function (\Zend\ServiceManager\ServiceManager $serviceManager) { $config = $serviceManager->get('Config'); $transport = new \Zend\Mail\Transport\Smtp(); $transport->setOptions(new \Zend\Mail\Transport\SmtpOptions($config['mail']['transport']['options'])); return $transport; //return smtp transport... }, 'mail.message' => function (\Zend\ServiceManager\ServiceManager $serviceManager) { $config = $serviceManager->get('Config'); $message = new \Zend\Mail\Message(); $headers = new \Zend\Mail\Headers(); $headers->addHeaders($config['mail']['message']['headers']); $message->setHeaders($headers)->setFrom($config['mail']['message']['from']); //uncomment this if you want send email around //$message->getHeaders()->addHeaderLine('EXTERNAL', 'true'); return $message; })), 'bjyauthorize' => array('guards' => array('BjyAuthorize\\Guard\\Controller' => array(array('controller' => 'User\\Controller\\Auth', 'action' => array('twitter', 'twitter-callback', 'facebook', 'facebook-callback'), 'roles' => array('guest', 'user')), array('controller' => 'User\\Controller\\Auth', 'action' => array('login', 'recover-password'), 'roles' => array('guest')), array('controller' => 'User\\Controller\\Auth', 'action' => array('logout'), 'roles' => array('user')), array('controller' => 'User\\Controller\\Signup', 'action' => array('confirm'), 'roles' => array('guest', 'user')), array('controller' => 'User\\Controller\\Signup', 'action' => array('index', 'forgot-password'), 'roles' => array('guest')), array('controller' => 'User\\Controller\\Mail', 'action' => array('index'), 'roles' => array('admin')), array('controller' => 'User\\Controller\\Management', 'action' => array('create'), 'roles' => array('admin')), array('controller' => 'User\\Controller\\Management', 'action' => array('grid'), 'roles' => array('guest', 'user', 'admin')), array('controller' => 'User\\Controller\\Management', 'action' => array('get-users'), 'roles' => array('guest', 'user', 'admin')), array('controller' => 'User\\Controller\\Profile', 'roles' => array('user')), array('controller' => 'User\\Controller\\Management', 'action' => array('index'), 'roles' => array('admin')), array('controller' => 'User\\Controller\\Management', 'action' => array('edit'), 'roles' => array('admin')), array('controller' => 'User\\Controller\\Management', 'action' => array('delete'), 'roles' => array('admin'))))), 'navigation' => array('default' => array(array('label' => 'User', 'controller' => 'user', 'pages' => array(array('label' => 'Create', 'controller' => 'management', 'action' => 'create', 'route' => 'user/default', 'controller_namespace' => 'User\\Controller\\Management', 'module' => 'User'), array('label' => 'All', 'controller' => 'management', 'action' => 'index', 'route' => 'user/default', 'controller_namespace' => 'User\\Controller\\Management', 'module' => 'User'))))));
/** * @return Zend\Mail\Message */ function tiki_get_basic_mail() { tiki_mail_setup(); $mail = new Zend\Mail\Message(); $mail->setEncoding('UTF-8'); $mail->getHeaders()->addHeaderLine('X-Tiki', 'yes'); return $mail; }
public function previewAction() { $this->updateLayoutWithIdentity(); if ($this->disallowRankLessThan(User::RANK_CORPORAL)) { return false; } $session = new SessionContainer('NightsWatch\\Event\\Create'); if (empty($session->name)) { $this->redirect()->toRoute('home', ['contoller' => 'event', 'action' => 'create']); return false; } $userRepo = $this->getEntityManager()->getRepository('NightsWatch\\Entity\\User'); $eventRepo = $this->getEntityManager()->getRepository('NightsWatch\\Entity\\Event'); $leader = $session->leader; if (!empty($leader)) { $leader = $userRepo->findOneBy(['username' => $leader]); } if (empty($leader)) { $leader = $this->getIdentityEntity(); } $newEvent = false; if (isset($session->id) && $session->id != false) { $event = $eventRepo->find($session->id); if (is_null($event)) { throw new Exception('No such event found'); } } else { $newEvent = true; $event = new Event(); } $event->name = $session->name; $event->description = $session->description; if ($newEvent) { $event->user = $this->getIdentityEntity(); } $event->start = new \DateTime($session->date . ' ' . $session->time); $event->region = $session->region; $event->leader = $leader; $event->type = $session->type; $offset = $session->offset + date('Z'); $add = $offset > 0 ? true : false; $offset = abs($offset); $interval = new \DateInterval('PT' . $offset . 'S'); if ($add) { $event->start->add($interval); } else { $event->start->sub($interval); } $event->lowestViewableRank = $session->rank; if ($this->getRequest()->isPost()) { $this->getEntityManager()->persist($event); $this->getEntityManager()->flush(); $event->user = $this->getIdentityEntity(); $session->name = ''; // Send out the Emails $sendSpecified = isset($session->sendemail) && (bool) $session->sendemail; $sendEmails = $newEvent || $sendSpecified; if ($sendEmails) { $criteria = Criteria::create()->where(Criteria::expr()->gte('rank', $event->lowestViewableRank)); /** @var User[] $users */ $users = $userRepo->matching($criteria); $mail = new \Zend\Mail\Message(); $mail->setSubject('[NightsWatch] Event: ' . $event->name); $mail->setFrom(new Address('*****@*****.**', $event->user->username)); $mail->setTo(new Address('*****@*****.**', 'Members')); $headers = $mail->getHeaders(); if ($newEvent) { $headers->addHeaderLine('Message-Id', '<event-' . $event->id . '@threads.minez-nightswatch.com>'); } else { $headers->addHeaderLine('References', '<event-' . $event->id . '@threads.minez-nightswatch.com>'); $headers->addHeaderLine('In-Reply-To', '<event-' . $event->id . '@threads.minez-nightswatch.com>'); } $headers->addHeaderLine('Threading-Id', '<event-' . $event->id . '@threads.minez-nightswatch.com>'); $mail->setEncoding('UTF-8'); $url = $this->url()->fromRoute('id', ['controller' => 'event', 'action' => 'view', 'id' => $event->id], ['force_canonical' => true]); $niceDate = $event->start->format('M j, Y'); $niceTime = $event->start->format('H:i T'); $region = $event->getRegionName(); // Create a signature $title = trim($event->user->getTitleOrRank()); if ($newEvent) { $lead = 'A new event has been posted to the calendar.'; } else { $lead = 'An event on the calendar has been updated with new, important information.'; } $event->description = "{$lead} All information concerning this event " . 'is classified and only available to members of rank ' . User::getRankName($event->lowestViewableRank) . " and up.\n\n" . 'You can read the details of this event at https://minez-nightswatch.com/event/' . $event->id . "\n\nEvent Details: \nDate: {$niceDate} \nTime: {$niceTime} \nRSVP: [{$url}]({$url}) " . ($event->region > 0 ? "\nRegion: {$region}" : '') . "\n\n" . "{$event->user->username} \n*{$title}*"; // Event Stuff // Not Yet Working. Not sure why. $start = clone $event->start; $start->setTimezone(new \DateTimeZone('UTC')); $dtstart = $start->format('Ymd\\THis\\Z'); $eventRaw = <<<CALENDAR BEGIN:VCALENDAR PRODID:-//NightsWatch//Nights Watch Event Creator//EN VERSION:2.0 CALSCALE:GREGORIAN METHOD:REQUEST BEGIN:VEVENT UID:event-{$event->id}@minez-nightswatch.com DTSTART:{$dtstart} ORGANIZER;CN=Night's Watch:noreply@minez-nightswatch.com SUMMARY:{$event->name} END:VEVENT END:VCALENDAR CALENDAR; $body = new MimeBody(); $bodyHtml = new MimePart($event->getParsedDescription()); $bodyHtml->type = Mime::TYPE_HTML; $bodyText = new MimePart($event->description); $bodyText->type = Mime::TYPE_TEXT; $bodyEvent = new MimePart($eventRaw); $bodyEvent->type = 'text/calendar'; $bodyEvent->disposition = Mime::DISPOSITION_INLINE; $bodyEvent->encoding = Mime::ENCODING_8BIT; $bodyEvent->filename = 'calendar.ics'; $body->setParts([$bodyHtml, $bodyText, $bodyEvent]); $mail->setBody($body); foreach ($users as $user) { if ($user->emailNotifications & User::EMAIL_ANNOUNCEMENT > 0) { $mail->addBcc(new Address($user->email, $user->username)); } } $transport = new Sendmail(); $transport->send($mail); } $this->redirect()->toRoute('id', ['controller' => 'event', 'id' => $event->id]); return false; } return new ViewModel(['event' => $event, 'user' => $this->getIdentityEntity()]); }
private function setSubject() { $this->message->setSubject($this->mail->subject); }
<?php require_once 'Zend/Loader/StandardAutoloader.php'; $loader = new Zend\Loader\StandardAutoloader(); $loader->register(); $text = new Zend\Mime\Part('Plain Text'); $text->encoding = Zend\Mime\Mime::ENCODING_QUOTEDPRINTABLE; $text->type = Zend\Mime\Mime::TYPE_TEXT; $text->charset = 'UTF-8'; $html = new Zend\Mime\Part('<b>HTML</b>'); $html->encoding = Zend\Mime\Mime::ENCODING_QUOTEDPRINTABLE; $html->type = Zend\Mime\Mime::TYPE_HTML; $html->charset = 'UTF-8'; $message = new Zend\Mime\Message(); $message->addPart($text); $message->addPart($html); $mail = new Zend\Mail\Message('UTF-8'); $mail->setFrom('*****@*****.**'); $mail->setSubject('ZF2 Multipart Mail'); $mail->setBody($message); $mail->addTo('*****@*****.**'); $transport = new Zend\Mail\Transport\Smtp(); $transport->send($mail);
protected function convertMailMessage($mail) { if (!$mail instanceof \Zend_Mail) { throw new \InvalidArgumentException('The message should be an instance of \\Zend_Mail'); } //convert zend_mail1 to zend\mail\message // \Zend_Debug::dump($mail->getFrom()); // \Zend_Debug::dump(get_class_methods($mail)); // \Zend_Debug::dump($mail->getHeader('To')); // \Zend_Debug::dump($mail->getHeaders()); $headers = new \Zend\Mail\Headers(); $_headers = []; foreach ($mail->getHeaders() as $headerName => $values) { foreach ($values as $key => $value) { if ($key !== 'append') { $_headers[$headerName][$key] = $value; } } } $headers->addHeaders($_headers); $headersEncoding = $mail->getHeaderEncoding(); $headers->setEncoding($headersEncoding); $_message = new \Zend\Mail\Message(); $_message->setHeaders($headers); $body = new \Zend\Mime\Message(); $charset = $mail->getCharset(); $text = $mail->getBodyText(); if (!empty($text)) { if ($text instanceof \Zend_Mime_Part) { $part = new \Zend\Mime\Part($text->getContent()); $part->encoding = $text->encoding; $part->type = $text->type; $part->charset = $text->charset; } elseif (is_string($text)) { $part = new \Zend\Mime\Part($text); $part->encoding = \Zend\Mime\Mime::ENCODING_QUOTEDPRINTABLE; $part->type = \Zend\Mime\Mime::TYPE_TEXT; $part->charset = $charset; } $body->addPart($part); } $html = $mail->getBodyHtml(); if (!empty($html)) { if ($html instanceof \Zend_Mime_Part) { $part = new \Zend\Mime\Part($html->getContent()); $part->encoding = $html->encoding; $part->type = $html->type; $part->charset = $html->charset; } elseif (is_string($html)) { $part = new \Zend\Mime\Part($html); $part->encoding = \Zend\Mime\Mime::ENCODING_QUOTEDPRINTABLE; $part->type = \Zend\Mime\Mime::TYPE_TEXT; $part->charset = $charset; } $body->addPart($part); } //@todo $mail->getParts() copy attachments $_message->setBody($body); // \Zend_Debug::dump($_message); // die; return $_message; }
/** * Sets the new login * @param string $newLogin */ public function setNewLogin($newLogin) { $this->data['new_username'] = $newLogin; $this->data['confirm_code'] = md5(serialize($_SERVER) . time()); $this->update(); ob_start(); require $this->db->baseDir . DIRECTORY_SEPARATOR . 'mail' . DIRECTORY_SEPARATOR . 'changelogin.php'; $html = new \Zend\Mime\Part(ob_get_clean()); $html->type = 'text/html'; $body = new \Zend\Mime\Message(); $body->setParts(array($html)); $message = new \Zend\Mail\Message(); $message->addTo($this->data['username'])->addFrom($GLOBALS['config']->mail_from)->setSubject('Conferma modifica email/username per accedere al sito ' . $GLOBALS['config']->siteName)->setBody($body); $GLOBALS['transport']->send($message); }
public function sendmailHTML($to_email, $to_name, $subject, $htmltext) { $message = new \Zend\Mail\Message(); $message->addTo($to_email, $to_name)->setFrom('*****@*****.**', 'DiscoveryCRM')->setSubject($subject); // $htmltext = '<b>heii, <i>sorry</i>, i\'m going late</b>'; if ($_SERVER['HTTP_HOST'] == 'localhost') { $transport = new \Zend\Mail\Transport\Smtp(); $options = new \Zend\Mail\Transport\SmtpOptions(array('host' => 'smtp.gmail.com', 'connection_class' => 'login', 'connection_config' => array('ssl' => 'tls', 'username' => '*****@*****.**', 'password' => 'Discovery@123'), 'port' => 587)); $html = new \Zend\Mime\Part($htmltext); $html->type = "text/html"; $body = new \Zend\Mime\Message(); $body->addPart($html); $message->setBody($body); $transport->setOptions($options); $transport->send($message); } else { $bodyPart = new \Zend\Mime\Message(); $bodyMessage = new \Zend\Mime\Part($htmltext); $bodyMessage->type = 'text/html'; $bodyPart->setParts(array($bodyMessage)); $message->setBody($bodyPart); $message->setEncoding('UTF-8'); $transport = new \Zend\Mail\Transport\Sendmail(); $transport->send($message); } return 1; }
public function reportAction() { $request = $this->getRequest(); if (!$request instanceof ConsoleRequest) { throw new \RuntimeException('Action only available from console.'); } $objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager'); $j = $request->getParam('delta'); $email = $request->getParam('email'); $org = $request->getParam('orgshortname'); $organisation = $objectManager->getRepository('Application\\Entity\\Organisation')->findBy(array('shortname' => $org)); if (!$organisation) { throw new \RuntimeException('Unable to find organisation.'); } else { $email = $organisation[0]->getIpoEmail(); if (empty($email)) { throw new \RuntimeException('Unable to find IPO email.'); } } $day = new \DateTime('now'); if ($j) { if ($j > 0) { $day->add(new \DateInterval('P' . $j . 'D')); } else { $j = -$j; $interval = new \DateInterval('P' . $j . 'D'); $interval->invert = 1; $day->add($interval); } } $day = $day->format(DATE_RFC2822); $criteria = Criteria::create()->where(Criteria::expr()->isNull('parent'))->andWhere(Criteria::expr()->eq('system', false))->orderBy(array('place' => Criteria::ASC)); $cats = $objectManager->getRepository('Application\\Entity\\Category')->matching($criteria); $eventsByCats = array(); foreach ($cats as $cat) { $category = array(); $category['name'] = $cat->getName(); $category['events'] = $objectManager->getRepository('Application\\Entity\\Event')->getEvents(null, $day, null, true, array($cat->getId())); $category['childs'] = array(); foreach ($cat->getChildren() as $subcat) { $subcategory = array(); $subcategory['events'] = $objectManager->getRepository('Application\\Entity\\Event')->getEvents(null, $day, null, true, array($subcat->getId())); $subcategory['name'] = $subcat->getName(); $category['childs'][] = $subcategory; } $eventsByCats[] = $category; } $pdf = new PdfModel(); $pdf->setOption('paperSize', 'a4'); $formatter = \IntlDateFormatter::create(\Locale::getDefault(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'UTC', \IntlDateFormatter::GREGORIAN, 'dd_LL_yyyy'); $pdf->setOption('filename', 'rapport_du_' . $formatter->format(new \DateTime($day))); $pdfView = new ViewModel($pdf); $pdfView->setTerminal(true)->setTemplate('application/report/daily')->setVariables(array('events' => $eventsByCats, 'day' => $day)); $html = $this->getServiceLocator()->get('viewpdfrenderer')->getHtmlRenderer()->render($pdfView); $engine = $this->getServiceLocator()->get('viewpdfrenderer')->getEngine(); $engine->load_html($html); $engine->render(); // creating directory if it doesn't exists if (!is_dir('data/reports')) { mkdir('data/reports'); } file_put_contents('data/reports/rapport_du_' . $formatter->format(new \DateTime($day)) . '.pdf', $engine->output()); if ($email) { // prepare body with file attachment $text = new \Zend\Mime\Part('Veuillez trouver ci-joint le rapport automatique de la journée du ' . $formatter->format(new \DateTime($day))); $text->type = \Zend\Mime\Mime::TYPE_TEXT; $text->charset = 'utf-8'; $fileContents = fopen('data/reports/rapport_du_' . $formatter->format(new \DateTime($day)) . '.pdf', 'r'); $attachment = new \Zend\Mime\Part($fileContents); $attachment->type = 'application/pdf'; $attachment->filename = 'rapport_du_' . $formatter->format(new \DateTime($day)) . '.pdf'; $attachment->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT; $attachment->encoding = \Zend\Mime\Mime::ENCODING_BASE64; $mimeMessage = new \Zend\Mime\Message(); $mimeMessage->setParts(array($text, $attachment)); $config = $this->serviceLocator->get('config'); $message = new \Zend\Mail\Message(); $message->addTo($organisation[0]->getIpoEmail())->addFrom($config['emailfrom'])->setSubject('Rapport automatique du ' . $formatter->format(new \DateTime($day)))->setBody($mimeMessage); $transport = new \Zend\Mail\Transport\Smtp(); $transportOptions = new \Zend\Mail\Transport\SmtpOptions($config['smtp']); $transport->setOptions($transportOptions); $transport->send($message); } }
public function sendErrorEmail($textError) { $objectManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager'); //TODO récupérer proprement l'organisation concernée $org = $objectManager->getRepository('Application\\Entity\\Organisation')->findAll(); $ipoEmail = $org[0]->getIpoEmail(); // prepare body with file attachment $text = new \Zend\Mime\Part($textError); $text->type = \Zend\Mime\Mime::TYPE_TEXT; $text->charset = 'utf-8'; $mimeMessage = new \Zend\Mime\Message(); $mimeMessage->setParts(array($text)); $config = $this->getServiceLocator()->get('config'); $message = new \Zend\Mail\Message(); $message->addTo($ipoEmail)->addFrom($config['emailfrom'])->setSubject("Erreur lors de l'import de l'AUP via NM B2B")->setBody($mimeMessage); $transport = new \Zend\Mail\Transport\Smtp(); $transportOptions = new \Zend\Mail\Transport\SmtpOptions($config['smtp']); $transport->setOptions($transportOptions); $transport->send($message); }
/** * Send an email to any email address * * @param mixed $from Email address or string: "name <email>" * @param mixed $to Email address or string: "name <email>" * @param string $subject The subject of the message * @param string $body The message body * @param array $params Optional parameters * @return bool * @throws NotificationException */ function notifications_html_handler_send_email($from, $to, $subject, $body, array $params = null) { $options = array('to' => $to, 'from' => $from, 'subject' => $subject, 'body' => $body, 'params' => $params, 'headers' => array("Content-Type" => "text/html; charset=UTF-8; format=flowed", "MIME-Version" => "1.0", "Content-Transfer-Encoding" => "8bit")); // $mail_params is passed as both params and return value. The former is for backwards // compatibility. The latter is so handlers can now alter the contents/headers of // the email by returning the array $options = elgg_trigger_plugin_hook('email', 'system', $options, $options); if (!is_array($options)) { // don't need null check: Handlers can't set a hook value to null! return (bool) $options; } try { if (empty($options['from'])) { $msg = "Missing a required parameter, '" . 'from' . "'"; throw new \NotificationException($msg); } if (empty($options['to'])) { $msg = "Missing a required parameter, '" . 'to' . "'"; throw new \NotificationException($msg); } $options['to'] = \Elgg\Mail\Address::fromString($options['to']); $options['from'] = \Elgg\Mail\Address::fromString($options['from']); $options['subject'] = elgg_strip_tags($options['subject']); $options['subject'] = html_entity_decode($options['subject'], ENT_QUOTES, 'UTF-8'); // Sanitise subject by stripping line endings $options['subject'] = preg_replace("/(\r\n|\r|\n)/", " ", $options['subject']); $options['subject'] = elgg_get_excerpt(trim($options['subject'], 80)); $message = new \Zend\Mail\Message(); foreach ($options['headers'] as $headerName => $headerValue) { $message->getHeaders()->addHeaderLine($headerName, $headerValue); } $message->setEncoding('UTF-8'); $message->addFrom($options['from']); $message->addTo($options['to']); $message->setSubject($options['subject']); $body = new Zend\Mime\Message(); $html = new \Zend\Mime\Part($options['body']); $html->type = "text/html"; $body->addPart($html); $files = elgg_extract('attachments', $options['params']); if (!empty($files) && is_array($files)) { foreach ($files as $file) { if (!$file instanceof \ElggFile) { continue; } $attachment = new \Zend\Mime\Part(fopen($file->getFilenameOnFilestore(), 'r')); $attachment->type = $file->getMimeType() ?: $file->detectMimeType(); $attachment->filename = $file->originalfilename ?: basename($file->getFilename()); $attachment->disposition = Zend\Mime\Mime::DISPOSITION_ATTACHMENT; $attachment->encoding = Zend\Mime\Mime::ENCODING_BASE64; $body->addPart($attachment); } } $message->setBody($body); $transport = notifications_html_handler_get_transport(); if (!$transport instanceof Zend\Mail\Transport\TransportInterface) { throw new \NotificationException("Invalid Email transport"); } $transport->send($message); } catch (\Exception $e) { elgg_log($e->getMessage(), 'ERROR'); return false; } return true; }
protected function setSubject() { $this->message->setSubject($this->mail->subject); }