Format an email object

@param  object $oEmail The raw email object

@return void
@throws \Nails\Common\Exception\FactoryException
3422
protected function formatObject(&$oEmail)
    {
        $oEmail->type = !empty($this->aEmailType[$oEmail->type]) ? $this->aEmailType[$oEmail->type] : null;

        if (empty($oEmail->type)) {
            throw new NailsException(
                'Invalid Email Type: email with ID #' . $oEmail->id . ' has an invalid email type.'
            );
        }

        // --------------------------------------------------------------------------

        //  Some fields can be manipulated by the contents of email_vars
        $oEmail->data = json_decode($oEmail->email_vars) ?: new \stdClass();
        unset($oEmail->email_vars);

        // --------------------------------------------------------------------------

        /**
         * If a subject is defined in the variables use that, if not check to see if one was
         * defined in the template; if not, fall back to a default subject
         */

        if (!empty($oEmail->data->email_subject)) {
            $oEmail->subject = $oEmail->data->email_subject;
        } elseif (!empty($oEmail->type->default_subject)) {
            $oEmail->subject = $oEmail->type->default_subject;
        } else {
            $oEmail->subject = 'An E-mail from ' . APP_NAME;
        }

        // --------------------------------------------------------------------------

        //  Template overrides
        if (!empty($oEmail->data->template_header)) {
            $oEmail->type->template_header = $oEmail->data->template_header;
        }

        if (!empty($oEmail->data->template_body)) {
            $oEmail->type->template_body = $oEmail->data->template_body;
        }

        if (!empty($oEmail->data->template_footer)) {
            $oEmail->type->template_footer = $oEmail->data->template_footer;
        }

        // --------------------------------------------------------------------------

        //  Who the email is being sent to
        $oEmail->to                      = new \stdClass();
        $oEmail->to->id                  = $oEmail->user_id;
        $oEmail->to->group_id            = $oEmail->user_group;
        $oEmail->to->email               = $oEmail->sent_to;
        $oEmail->to->username            = $oEmail->username;
        $oEmail->to->password            = $oEmail->user_password;
        $oEmail->to->first_name          = $oEmail->first_name;
        $oEmail->to->last_name           = $oEmail->last_name;
        $oEmail->to->profile_img         = $oEmail->profile_img;
        $oEmail->to->gender              = $oEmail->gender;
        $oEmail->to->gender              = $oEmail->gender;
        $oEmail->to->email_verified      = $oEmail->email_verified;
        $oEmail->to->email_verified_code = $oEmail->email_verified_code;

        unset($oEmail->user_id);
        unset($oEmail->sent_to);
        unset($oEmail->username);
        unset($oEmail->first_name);
        unset($oEmail->last_name);
        unset($oEmail->profile_img);
        unset($oEmail->gender);
        unset($oEmail->user_group);
        unset($oEmail->user_password);
        unset($oEmail->email_verified);
        unset($oEmail->email_verified_code);

        //  Who the email is being sent from
        $oEmail->from        = new \stdClass();
        $oEmail->from->name  = !empty($oEmail->data->email_from_name) ? $oEmail->data->email_from_name : $this->from->name;
        $oEmail->from->email = !empty($oEmail->data->email_from_email) ? $oEmail->data->email_from_email : $this->from->email;

        //  Template details
        $oEmail->template               = new \stdClass();
        $oEmail->template->header       = new \stdClass();
        $oEmail->template->header->html = $oEmail->type->template_header;
        $oEmail->template->header->text = $oEmail->type->template_header . '_plaintext';
        $oEmail->template->body         = new \stdClass();
        $oEmail->template->body->html   = $oEmail->type->template_body;
        $oEmail->template->body->text   = $oEmail->type->template_body . '_plaintext';
        $oEmail->template->footer       = new \stdClass();
        $oEmail->template->footer->html = $oEmail->type->template_footer;
        $oEmail->template->footer->text = $oEmail->type->template_footer . '_plaintext';

        // --------------------------------------------------------------------------

        //  Add some extra, common variables for the template
        $oEmail->data->emailType = $oEmail->type;
        $oEmail->data->emailRef  = $oEmail->ref;
        $oEmail->data->sentFrom  = $oEmail->from;
        $oEmail->data->sentTo    = $oEmail->to;
        $oEmail->data->siteUrl   = site_url();

        //  Common URLs
        $oEmail->data->url = new \stdClass();

        //  AutoLogin
        $oEmail->data->url->autoLogin = '';

        // //  Check login URLs are allowed
        $this->oCi->config->load('auth/auth');

        if (!empty($oEmail->to->id) && $this->oCi->config->item('authEnableHashedLogin')) {
            $sIdHash                      = md5($oEmail->to->id);
            $sPwHash                      = md5($oEmail->to->password);
            $oEmail->data->url->autoLogin = site_url('auth/login/with_hashes/' . $sIdHash . '/' . $sPwHash);
        }

        //  View Online
        $iTime                         = time();
        $sHash                         = $this->generateHash($oEmail->data->emailRef, $iTime);
        $oEmail->data->url->viewOnline = site_url(
            'email/view/' . $oEmail->data->emailRef . '/' . $iTime . '/' . $sHash
        );

        //  1-Click Unsubscribe
        $oEmail->data->url->unsubscribe = '';
        if ($oEmail->type->isUnsubscribable && !empty($oEmail->to->id)) {

            $sUrl = site_url('email/unsubscribe?token=');

            /**
             * Bit of a hack; keep trying until there's no + symbol in the hash, try up to
             * 20 times before giving up @TODO: make this less hacky
             */

            $iCounter  = 0;
            $iAttempts = 20;
            $oEncrypt  = Factory::service('Encrypt');

            do {

                $sToken = $oEncrypt->encode(
                    $oEmail->type->slug . '|' . $oEmail->data->emailRef . '|' . $oEmail->to->id,
                    APP_PRIVATE_KEY
                );
                $iCounter++;

            } while ($iCounter <= $iAttempts && strpos($sToken, '+') !== false);

            //  Link, autologin if possible
            if (!empty($oEmail->data->url->autoLogin)) {
                $oEmail->data->url->unsubscribe = $oEmail->data->url->autoLogin . '?return_to=' . urlencode($sUrl . $sToken);
            } else {
                $oEmail->data->url->unsubscribe = $sUrl . $sToken;
            }
        }

        //  Tracker Image (not on view online links though)
        $oEmail->data->url->trackerImg = '';
        if (!preg_match('/^email\/view\/[a-zA-Z0-9]+\/[0-9]+\/[a-zA-Z0-9]+$/', uri_string())) {
            $iTime                         = time();
            $sHash                         = $this->generateHash($oEmail->data->emailRef, $iTime);
            $sImgSrc                       = site_url('email/tracker/' . $oEmail->data->emailRef . '/' . $iTime . '/' . $sHash) . '/0.gif';
            $oEmail->data->url->trackerImg = $sImgSrc;
        }

        // --------------------------------------------------------------------------

        $oMustache = Factory::service('Mustache');

        //  Subject
        $oEmail->subject = $oMustache->render($oEmail->subject, $oEmail->data);

        //  Add the rendered subject to the data array so the body can sue it
        $oEmail->data->email_subject = $oEmail->subject;

        //  Body
        $oEmail->body = new \stdClass();

        //  HTML Version
        $oView              = Factory::service('View');
        $oEmail->body->html = $oView->load(
            $oEmail->template->header->html,
            ['emailObject' => $oEmail],
            true
        );
        $oEmail->body->html .= $oView->load(
            $oEmail->template->body->html,
            ['emailObject' => $oEmail],
            true
        );
        $oEmail->body->html .= $oView->load(
            $oEmail->template->footer->html,
            ['emailObject' => $oEmail],
            true
        );

        //  Plain text version
        $oEmail->body->text = $oView->load(
            $oEmail->template->header->text,
            ['emailObject' => $oEmail],
            true
        );
        $oEmail->body->text .= $oView->load(
            $oEmail->template->body->text,
            ['emailObject' => $oEmail],
            true
        );
        $oEmail->body->text .= $oView->load(
            $oEmail->template->footer->text,
            ['emailObject' => $oEmail],
            true
        );

        $oEmail->body->html = $oMustache->render($oEmail->body->html, $oEmail->data);
        $oEmail->body->text = $oMustache->render($oEmail->body->text, $oEmail->data);
    }
732577
private function _baseMailSetup($oOrder, $sTemplate, $sSubject)
    {
        $oConfig = $this->_getContainer()->getConfig();

        $iOrderLang = $this->_getContainer()->getLoginClient()->getOrderLanguageId($oOrder);
        $oShop = $this->_getShop($iOrderLang);

        //set mail params (from, fromName, smtp)
        $this->_setMailParams($oShop);

        //create messages
        $oLang = $this->_getContainer()->getLanguage();
        $oSmarty = $this->_getSmarty();

        $this->setViewData('order', $oOrder);
        $this->setViewData('shopTemplateDir', $oConfig->getTemplateDir(false));

        // Process view data array through oxoutput processor
        $this->_processViewArray();

        // dodger #1469 - we need to patch security here as we do not use standard template dir, so smarty stops working
        $aStore['INCLUDE_ANY'] = $oSmarty->security_settings['INCLUDE_ANY'];
        //V send email in order language
        $iOldTplLang = $oLang->getTplLanguage();
        $iOldBaseLang = $oLang->getTplLanguage();
        $oLang->setTplLanguage($iOrderLang);
        $oLang->setBaseLanguage($iOrderLang);
        $oSmarty->security_settings['INCLUDE_ANY'] = true;
        // force non admin to get correct paths (tpl, img)
        $oConfig->setAdminMode(false);

        $this->setBody($oSmarty->fetch($sTemplate));
        //Set subject
        $this->setSubject($oLang->translateString($sSubject));

        $oConfig->setAdminMode(true);
        $oLang->setTplLanguage($iOldTplLang);
        $oLang->setBaseLanguage($iOldBaseLang);

        // set it back
        $oSmarty->security_settings['INCLUDE_ANY'] = $aStore['INCLUDE_ANY'];

        $sFullName = $oOrder->getFieldData('oxbillfname').' '.$oOrder->getFieldData('oxbilllname');

        $this->setRecipient($oOrder->getFieldData('oxbillemail'), $sFullName);
        $this->setReplyTo($oShop->getFieldData('oxorderemail'), $oShop->getFieldData('oxname'));

        return $this->send();
    }
1204141
public function setEmail($email)
    {
        $this->email = $email;
        $this->referenceId = null;
        $this->executed = false;
        return $this;
    }
934349
public function obfuscate($email)
    {
        $output = null;
        for ($i = 0; $i < strlen($email); $i++) {
            $output .= '&#'.ord($email[$i]).';';
        }
        
        return $output;
    }
918559
public static function protectEmail($email)
    {
        $chunks = explode('@', $email);
        $chunks[0] = substr($chunks[0], 0, 2) . '****';
        return implode('@', $chunks);
    }
285293
public function setSenderEmailAddress($email)
    {
        if (!$this->validateHeaderFieldValue($email)) {
            throw new EmailValidationException(__('Sender Email Address can not contain carriage return or newlines.'));
        }

        $this->_sender_email_address = $email;
    }
642775
public function setEmailTemplates(EmailInterface $email)
    {
        if ($email->getLayout()) {
            // call of getLayoutBody set locale on layout
            $body = $email->getLayoutBody();
            
            // now we can compute correctly the key cache
            $layoutSuffix = $email->getLayout()->getChecksum();

            $this->setTemplate(sprintf('layout_%s', $layoutSuffix), $body);
            $this->updateDates[sprintf('layout_%s', $layoutSuffix)] = $email->getLayout()->getLastModifiedTimestamp();

            $content = strtr('{% extends \'<layout>\' %}{% block content %}<content>{% endblock %}', array(
                '<layout>'  => sprintf('layout_%s', $layoutSuffix),
                '<content>' => $email->getBody(),
            ));

        } else {
            $content = $email->getBody();
        }

        $emailSuffix = $email->getChecksum();

        $this->setTemplate(sprintf('html_content_%s', $emailSuffix), $content);
        $this->setTemplate(sprintf('text_content_%s', $emailSuffix), $email->getBodyText());
        $this->setTemplate(sprintf('subject_%s', $emailSuffix), $email->getSubject());
        $this->setTemplate(sprintf('from_name_%s', $emailSuffix), $email->getFromName());
        $this->setTemplate(sprintf('from_address_%s', $emailSuffix), $email->getFromAddress());

        // keep updated at to be able to check if the template is fresh
        $this->updateDates[sprintf('html_content_%s', $emailSuffix)] = $email->getLastModifiedTimestamp();
        $this->updateDates[sprintf('text_content_%s', $emailSuffix)] = $email->getLastModifiedTimestamp();
        $this->updateDates[sprintf('subject_%s', $emailSuffix)] = $email->getLastModifiedTimestamp();
        $this->updateDates[sprintf('from_name_%s', $emailSuffix)] = $email->getLastModifiedTimestamp();
        $this->updateDates[sprintf('from_address_%s', $emailSuffix)] = $email->getLastModifiedTimestamp();
    }
1256381
protected function _sendData($email)
    {
        $this->_smtpSend('DATA', '354');

        $headers = $this->_headersToString($this->_prepareMessageHeaders($email));
        $message = $this->_prepareMessage($email);

        $this->_smtpSend($headers . "\r\n\r\n" . $message . "\r\n\r\n\r\n.");
        $this->_content = ['headers' => $headers, 'message' => $message];
    }
113450
public function send(Email $email)
    {
        $eol = PHP_EOL;
        if (isset($this->_config['eol'])) {
            $eol = $this->_config['eol'];
        }
        $headers = $email->getHeaders(['from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc']);
        $to = $headers['To'];
        unset($headers['To']);
        foreach ($headers as $key => $header) {
            $headers[$key] = str_replace(["\r", "\n"], '', $header);
        }
        $headers = $this->_headersToString($headers, $eol);
        $subject = str_replace(["\r", "\n"], '', $email->getSubject());
        $to = str_replace(["\r", "\n"], '', $to);

        $message = implode($eol, $email->message());

        $params = isset($this->_config['additionalParameters']) ? $this->_config['additionalParameters'] : null;
        $this->_mail($to, $subject, $message, $headers, $params);

        $headers .= $eol . 'To: ' . $to;
        $headers .= $eol . 'Subject: ' . $subject;

        return ['headers' => $headers, 'message' => $message];
    }
289472
private function setEntete() {
        $params = "MIME-Version: 1.0\r\n";
        $params .= "Content-type: $this->type; charset=$this->encodage\r\n";
        $from = "From: $this->expediteur_nom <$this->expediteur_email>\r\n";
        $to = "To: $this->destinataire_nom <$this->destinataire_email>\r\n";
        $replay = "Reply-To: $this->expediteur_email\r\n";
        $this->entete = $from . $to . $replay . $params;
    }
1032783
protected function prepareEmails(array $emails)
    {
        foreach ($emails as $email) {
            $email->setStatus(SpoolEmailStatus::STATUS_SENDING);
            $email->setSentAt(null);
            $this->om->persist($email);
        }

        $this->om->flush();
        reset($emails);

        return $emails;
    }
429282
private function SendTo($email)
    {
        $texts = array();
        $subject = Trans('Core.Forms.Form.DefaultSubject');
        $mailer = new PHPMailer();
        $mailer->isHTML(false);
        $mailer->CharSet = 'UTF-8';
        $mailer->setFrom($this->form->GetSendFrom());
        foreach($this->Elements()->GetElements() as $element)
        {
            if ($element instanceof Fields\Submit)
            {
                continue;
            }
            $name = $element->GetName();
            if ($name == 'Subject')
            {
                $subject = $this->Value($name);
            }
            else if ($name == 'ReplyTo')
            {
                $mailer->addReplyTo($this->Value($name));
            }
            $texts[] = $name . ": " . $this->Value($name);
        }
        $message = join("\r\n", $texts);
        $mailer->Subject = $subject;
        $mailer->Body = $message;
        $mailer->addAddress($email);
        $mailer->send();
    }
598397
public function index()
    {
        if (!userHasPermission('admin:email:utilities:sendTest')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        //  Page Title
        $this->data['page']->title = 'Send a Test Email';

        // --------------------------------------------------------------------------

        $oInput = Factory::service('Input');
        if ($oInput->post()) {

            //  Form validation and update
            $oFormValidation = Factory::service('FormValidation');

            //  Define rules
            $oFormValidation->set_rules('recipient', '', 'required|valid_email');

            //  Set Messages
            $oFormValidation->set_message('required', lang('fv_required'));
            $oFormValidation->set_message('valid_email', lang('fv_valid_email'));

            //  Execute
            if ($oFormValidation->run()) {

                //  Prepare data
                $oNow   = Factory::factory('DateTime');
                $oEmail = (object) [
                    'type'     => 'test_email',
                    'to_email' => $oInput->post('recipient', true),
                    'data'     => [
                        'sentAt' => $oNow->format('Y-m-d H:i:s'),
                    ],
                ];

                //  Send the email
                $oEmailer = Factory::service('Emailer', 'nails/module-email');
                if ($oEmailer->send($oEmail)) {

                    $this->data['success'] = '<strong>Done!</strong> Test email successfully sent to <strong>';
                    $this->data['success'] .= $oEmail->to_email . '</strong> at ' . toUserDatetime();

                } else {

                    echo '<h1>Sending Failed, debugging data below:</h1>';
                    echo $oEmailer->print_debugger();
                    return;
                }
            }
        }

        // --------------------------------------------------------------------------

        //  Load views
        Helper::loadView('index');
    }
4322
public function setOrganizer(string $email) : void
    {
        if ('' !== $email) {
            $this->event->setOrganizer(
                new Organizer($email, ['MAILTO' => $email])
            );
        }
    }
331924
public function setFrom($email, $name = null)
    {
        if ($email instanceof From) {
            $this->from = $email;
        } else {

            if (
                is_string($email) && filter_var($email, FILTER_VALIDATE_EMAIL)
            ) {
                $this->from = new From($email, $name);
            } else {
                throw new TypeException(
                    '$email must be valid and of type string.'
                );
            }

        }
        return;
    }
1347437
public function report(Exception $exception)
    {
        $enableEmailExceptions = config('exceptions.emailExceptionEnabled');

        if ($enableEmailExceptions === '') {
            $enableEmailExceptions = config('exceptions.emailExceptionEnabledDefault');
        }

        if ($enableEmailExceptions) {
            if ($this->shouldReport($exception)) {
                $this->sendEmail($exception);
            }
        }

        parent::report($exception);
    }
17345
public function setType($type = self::TYPE_TEXT) {
		if (!in_array($type, array(self::TYPE_TEXT, self::TYPE_HTML))) {
			throw new MailException('invalid type: ' . $type);
		}
		$this->type = $type;
	}