Example #1
0
 /**
  * Send a email using t3lib_htmlmail or the new swift mailer
  * It depends on the TYPO3 version
  */
 public static function sendEmail($to, $subject, $message, $type = 'plain', $charset = 'utf-8', $files = array())
 {
     $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
     $mail->setTo(explode(',', $to));
     $mail->setSubject($subject);
     $mail->setCharset($charset);
     $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
     $mail->setFrom($from);
     $mail->setReplyTo($from);
     // add Files
     if (!empty($files)) {
         foreach ($files as $file) {
             $mail->attach(Swift_Attachment::fromPath($file));
         }
     }
     // add Plain
     if ($type == 'plain') {
         $mail->addPart($message, 'text/plain');
     }
     // add HTML
     if ($type == 'html') {
         $mail->setBody($message, 'text/html');
     }
     // send
     $mail->send();
 }
 /**
  * @param \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager
  * @return void
  */
 public function injectConfigurationManager(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager)
 {
     parent::injectConfigurationManager($configurationManager);
     $defaultSettings = array('dateFormat' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], 'login' => array('page' => $this->getFrontendController()->id), 'passwordReset' => array('loginOnSuccess' => FALSE, 'mail' => array('from' => MailUtility::getSystemFromAddress(), 'subject' => 'Password reset request'), 'page' => $this->getFrontendController()->id, 'token' => array('lifetime' => 86400)));
     $settings = $defaultSettings;
     ArrayUtility::mergeRecursiveWithOverrule($settings, $this->settings, TRUE, FALSE);
     $this->settings = $settings;
 }
Example #3
0
 /**
  * @param array $from  array('email' => '', 'name' => '')
  * @param array $to array('email' => '', 'name' => '')
  * @param $subject
  * @param $body
  * @return boolean
  */
 public static function sendNotification(array $from, array $to, $subject, $body)
 {
     if (!count($from)) {
         $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
     }
     $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
     return $mail->setFrom(array($from['email'] => $from['name']))->setTo(array($to['email'] => $to['name']))->setSubject($subject)->setBody($body)->send();
 }
 /**
  * Initialize all actions
  *
  * @return void
  */
 protected function initializeAction()
 {
     // Apply default settings
     $defaultSettings = array('dateFormat' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], 'login' => array('page' => $this->getFrontendController()->id), 'passwordReset' => array('loginOnSuccess' => FALSE, 'mail' => array('from' => MailUtility::getSystemFromAddress(), 'subject' => 'Password reset request'), 'page' => $this->getFrontendController()->id, 'token' => array('lifetime' => 86400)));
     $settings = $defaultSettings;
     ArrayUtility::mergeRecursiveWithOverrule($settings, $this->settings, TRUE, FALSE);
     $this->settings = $settings;
     // Make global form data (as expected by the CMS core) available
     $formData = GeneralUtility::_GET();
     ArrayUtility::mergeRecursiveWithOverrule($formData, GeneralUtility::_POST());
     $this->request->setArgument('formData', $formData);
 }
Example #5
0
 /**
  * Render the given element
  *
  * @return array
  */
 public function renderInternal()
 {
     $headerWrap = MailUtility::breakLinesForEmail(trim($this->contentObject->data['header']), LF, Configuration::getPlainTextWith());
     $subHeaderWrap = MailUtility::breakLinesForEmail(trim($this->contentObject->data['subheader']), LF, Configuration::getPlainTextWith());
     // align
     $header = array_merge(GeneralUtility::trimExplode(LF, $headerWrap, TRUE), GeneralUtility::trimExplode(LF, $subHeaderWrap, TRUE));
     if ($this->contentObject->data['header_position'] == 'right') {
         foreach ($header as $key => $l) {
             $l = trim($l);
             $header[$key] = str_pad(' ', Configuration::getPlainTextWith() - strlen($l), ' ', STR_PAD_LEFT) . $l;
         }
     } elseif ($this->contentObject->data['header_position'] == 'center') {
         foreach ($header as $key => $l) {
             $l = trim($l);
             $header[$key] = str_pad(' ', floor((Configuration::getPlainTextWith() - strlen($l)) / 2), ' ', STR_PAD_LEFT) . $l;
         }
     }
     $header = implode(LF, $header);
     $lines[] = $header;
     return $lines;
 }
 /**
  * Logs message to the system log.
  * This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors.
  * If you want to implement the sysLog in your applications, simply add lines like:
  * \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog('[write message in English here]', 'extension_key', 'severity');
  *
  * @param string $msg Message (in English).
  * @param string $extKey Extension key (from which extension you are calling the log) or "Core
  * @param integer $severity \TYPO3\CMS\Core\Utility\GeneralUtility::SYSLOG_SEVERITY_* constant
  * @return void
  */
 public static function sysLog($msg, $extKey, $severity = 0)
 {
     $severity = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($severity, 0, 4);
     // Is message worth logging?
     if ((int) $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'] > $severity) {
         return;
     }
     // Initialize logging
     if (!$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) {
         self::initSysLog();
     }
     // Do custom logging
     if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
         $params = array('msg' => $msg, 'extKey' => $extKey, 'backTrace' => debug_backtrace(), 'severity' => $severity);
         $fakeThis = FALSE;
         foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
             self::callUserFunction($hookMethod, $params, $fakeThis);
         }
     }
     // TYPO3 logging enabled?
     if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog']) {
         return;
     }
     $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
     $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
     // Use all configured logging options
     foreach (explode(';', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog'], 2) as $log) {
         list($type, $destination, $level) = explode(',', $log, 4);
         // Is message worth logging for this log type?
         if ((int) $level > $severity) {
             continue;
         }
         $msgLine = ' - ' . $extKey . ': ' . $msg;
         // Write message to a file
         if ($type == 'file') {
             $file = fopen($destination, 'a');
             if ($file) {
                 fwrite($file, date($dateFormat . ' ' . $timeFormat) . $msgLine . LF);
                 fclose($file);
                 self::fixPermissions($destination);
             }
         } elseif ($type == 'mail') {
             list($to, $from) = explode('/', $destination);
             if (!self::validEmail($from)) {
                 $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
             }
             /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
             $mail = self::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
             $mail->setTo($to)->setFrom($from)->setSubject('Warning - error in TYPO3 installation')->setBody('Host: ' . $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . LF . 'Extension: ' . $extKey . LF . 'Severity: ' . $severity . LF . LF . $msg);
             $mail->send();
         } elseif ($type == 'error_log') {
             error_log($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . $msgLine, 0);
         } elseif ($type == 'syslog') {
             $priority = array(LOG_INFO, LOG_NOTICE, LOG_WARNING, LOG_ERR, LOG_CRIT);
             syslog($priority[(int) $severity], $msgLine);
         }
     }
 }
 /**
  * Build and send warning email when new broken links were found
  *
  * @param string $pageSections Content of page section
  * @param array $modTsConfig TSconfig array
  * @return bool TRUE if mail was sent, FALSE if or not
  * @throws \Exception if required modTsConfig settings are missing
  */
 protected function reportEmail($pageSections, array $modTsConfig)
 {
     $content = $this->templateService->substituteSubpart($this->templateMail, '###PAGE_SECTION###', $pageSections);
     /** @var array $markerArray */
     $markerArray = array();
     /** @var array $validEmailList */
     $validEmailList = array();
     /** @var bool $sendEmail */
     $sendEmail = true;
     $markerArray['totalBrokenLink'] = $this->totalBrokenLink;
     $markerArray['totalBrokenLink_old'] = $this->oldTotalBrokenLink;
     // Hook
     if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['linkvalidator']['reportEmailMarkers'])) {
         foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['linkvalidator']['reportEmailMarkers'] as $userFunc) {
             $params = array('pObj' => &$this, 'markerArray' => $markerArray);
             $newMarkers = GeneralUtility::callUserFunction($userFunc, $params, $this);
             if (is_array($newMarkers)) {
                 $markerArray = $newMarkers + $markerArray;
             }
             unset($params);
         }
     }
     $content = $this->templateService->substituteMarkerArray($content, $markerArray, '###|###', true, true);
     /** @var $mail MailMessage */
     $mail = GeneralUtility::makeInstance(MailMessage::class);
     if (empty($modTsConfig['mail.']['fromemail'])) {
         $modTsConfig['mail.']['fromemail'] = MailUtility::getSystemFromAddress();
     }
     if (empty($modTsConfig['mail.']['fromname'])) {
         $modTsConfig['mail.']['fromname'] = MailUtility::getSystemFromName();
     }
     if (GeneralUtility::validEmail($modTsConfig['mail.']['fromemail'])) {
         $mail->setFrom(array($modTsConfig['mail.']['fromemail'] => $modTsConfig['mail.']['fromname']));
     } else {
         throw new \Exception($this->getLanguageService()->sL('LLL:EXT:linkvalidator/Resources/Private/Language/locallang.xlf:tasks.error.invalidFromEmail'), '1295476760');
     }
     if (GeneralUtility::validEmail($modTsConfig['mail.']['replytoemail'])) {
         $mail->setReplyTo(array($modTsConfig['mail.']['replytoemail'] => $modTsConfig['mail.']['replytoname']));
     }
     if (!empty($modTsConfig['mail.']['subject'])) {
         $mail->setSubject($modTsConfig['mail.']['subject']);
     } else {
         throw new \Exception($this->getLanguageService()->sL('LLL:EXT:linkvalidator/Resources/Private/Language/locallang.xlf:tasks.error.noSubject'), '1295476808');
     }
     if (!empty($this->email)) {
         // Check if old input field value is still there and save the value a
         if (strpos($this->email, ',') !== false) {
             $emailList = GeneralUtility::trimExplode(',', $this->email, true);
             $this->email = implode(LF, $emailList);
             $this->save();
         } else {
             $emailList = GeneralUtility::trimExplode(LF, $this->email, true);
         }
         foreach ($emailList as $emailAdd) {
             if (!GeneralUtility::validEmail($emailAdd)) {
                 throw new \Exception($this->getLanguageService()->sL('LLL:EXT:linkvalidator/Resources/Private/Language/locallang.xlf:tasks.error.invalidToEmail'), '1295476821');
             } else {
                 $validEmailList[] = $emailAdd;
             }
         }
     }
     if (is_array($validEmailList) && !empty($validEmailList)) {
         $mail->setTo($validEmailList);
     } else {
         $sendEmail = false;
     }
     if ($sendEmail) {
         $mail->setBody($content, 'text/html');
         $mail->send();
     }
     return $sendEmail;
 }
Example #8
0
    /**
     * Send an email notification to users in workspace
     *
     * @param array $stat Workspace access array from \TYPO3\CMS\Core\Authentication\BackendUserAuthentication::checkWorkspace()
     * @param int $stageId New Stage number: 0 = editing, 1= just ready for review, 10 = ready for publication, -1 = rejected!
     * @param string $table Table name of element (or list of element names if $id is zero)
     * @param int $id Record uid of element (if zero, then $table is used as reference to element(s) alone)
     * @param string $comment User comment sent along with action
     * @param DataHandler $tcemainObj TCEmain object
     * @param array $notificationAlternativeRecipients List of recipients to notify instead of be_users selected by sys_workspace, list is generated by workspace extension module
     * @return void
     */
    protected function notifyStageChange(array $stat, $stageId, $table, $id, $comment, DataHandler $tcemainObj, array $notificationAlternativeRecipients = array())
    {
        $workspaceRec = BackendUtility::getRecord('sys_workspace', $stat['uid']);
        // So, if $id is not set, then $table is taken to be the complete element name!
        $elementName = $id ? $table . ':' . $id : $table;
        if (!is_array($workspaceRec)) {
            return;
        }
        // Get the new stage title from workspaces library, if workspaces extension is installed
        if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
            $stageService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\StagesService::class);
            $newStage = $stageService->getStageTitle((int) $stageId);
        } else {
            // @todo CONSTANTS SHOULD BE USED - tx_service_workspace_workspaces
            // @todo use localized labels
            // Compile label:
            switch ((int) $stageId) {
                case 1:
                    $newStage = 'Ready for review';
                    break;
                case 10:
                    $newStage = 'Ready for publishing';
                    break;
                case -1:
                    $newStage = 'Element was rejected!';
                    break;
                case 0:
                    $newStage = 'Rejected element was noticed and edited';
                    break;
                default:
                    $newStage = 'Unknown state change!?';
            }
        }
        if (count($notificationAlternativeRecipients) == 0) {
            // Compile list of recipients:
            $emails = array();
            switch ((int) $stat['stagechg_notification']) {
                case 1:
                    switch ((int) $stageId) {
                        case 1:
                            $emails = $this->getEmailsForStageChangeNotification($workspaceRec['reviewers']);
                            break;
                        case 10:
                            $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], TRUE);
                            break;
                        case -1:
                            // List of elements to reject:
                            $allElements = explode(',', $elementName);
                            // Traverse them, and find the history of each
                            foreach ($allElements as $elRef) {
                                list($eTable, $eUid) = explode(':', $elRef);
                                $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('log_data,tstamp,userid', 'sys_log', 'action=6 and details_nr=30
												AND tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($eTable, 'sys_log') . '
												AND recuid=' . (int) $eUid, '', 'uid DESC');
                                // Find all implicated since the last stage-raise from editing to review:
                                foreach ($rows as $dat) {
                                    $data = unserialize($dat['log_data']);
                                    $emails = $this->getEmailsForStageChangeNotification($dat['userid'], TRUE) + $emails;
                                    if ($data['stage'] == 1) {
                                        break;
                                    }
                                }
                            }
                            break;
                        case 0:
                            $emails = $this->getEmailsForStageChangeNotification($workspaceRec['members']);
                            break;
                        default:
                            $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], TRUE);
                    }
                    break;
                case 10:
                    $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], TRUE);
                    $emails = $this->getEmailsForStageChangeNotification($workspaceRec['reviewers']) + $emails;
                    $emails = $this->getEmailsForStageChangeNotification($workspaceRec['members']) + $emails;
                    break;
                default:
                    // Do nothing
            }
        } else {
            $emails = $notificationAlternativeRecipients;
        }
        // prepare and then send the emails
        if (count($emails)) {
            // Path to record is found:
            list($elementTable, $elementUid) = explode(':', $elementName);
            $elementUid = (int) $elementUid;
            $elementRecord = BackendUtility::getRecord($elementTable, $elementUid);
            $recordTitle = BackendUtility::getRecordTitle($elementTable, $elementRecord);
            if ($elementTable == 'pages') {
                $pageUid = $elementUid;
            } else {
                BackendUtility::fixVersioningPid($elementTable, $elementRecord);
                $pageUid = $elementUid = $elementRecord['pid'];
            }
            // fetch the TSconfig settings for the email
            // old way, options are TCEMAIN.notificationEmail_body/subject
            $TCEmainTSConfig = $tcemainObj->getTCEMAIN_TSconfig($pageUid);
            // new way, options are
            // pageTSconfig: tx_version.workspaces.stageNotificationEmail.subject
            // userTSconfig: page.tx_version.workspaces.stageNotificationEmail.subject
            $pageTsConfig = BackendUtility::getPagesTSconfig($pageUid);
            $emailConfig = $pageTsConfig['tx_version.']['workspaces.']['stageNotificationEmail.'];
            $markers = array('###RECORD_TITLE###' => $recordTitle, '###RECORD_PATH###' => BackendUtility::getRecordPath($elementUid, '', 20), '###SITE_NAME###' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'], '###SITE_URL###' => GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir, '###WORKSPACE_TITLE###' => $workspaceRec['title'], '###WORKSPACE_UID###' => $workspaceRec['uid'], '###ELEMENT_NAME###' => $elementName, '###NEXT_STAGE###' => $newStage, '###COMMENT###' => $comment, '###USER_REALNAME###' => $tcemainObj->BE_USER->user['realName'], '###USER_FULLNAME###' => $tcemainObj->BE_USER->user['realName'], '###USER_USERNAME###' => $tcemainObj->BE_USER->user['username']);
            // add marker for preview links if workspace extension is loaded
            if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
                $this->workspaceService = GeneralUtility::makeInstance(\TYPO3\CMS\Workspaces\Service\WorkspaceService::class);
                // only generate the link if the marker is in the template - prevents database from getting to much entries
                if (GeneralUtility::isFirstPartOfStr($emailConfig['message'], 'LLL:')) {
                    $tempEmailMessage = $GLOBALS['LANG']->sL($emailConfig['message']);
                } else {
                    $tempEmailMessage = $emailConfig['message'];
                }
                if (strpos($tempEmailMessage, '###PREVIEW_LINK###') !== FALSE) {
                    $markers['###PREVIEW_LINK###'] = $this->workspaceService->generateWorkspacePreviewLink($elementUid);
                }
                unset($tempEmailMessage);
                $markers['###SPLITTED_PREVIEW_LINK###'] = $this->workspaceService->generateWorkspaceSplittedPreviewLink($elementUid, TRUE);
            }
            // Hook for preprocessing of the content for formmails:
            if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/version/class.tx_version_tcemain.php']['notifyStageChange-postModifyMarkers'])) {
                foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/version/class.tx_version_tcemain.php']['notifyStageChange-postModifyMarkers'] as $_classRef) {
                    $_procObj =& GeneralUtility::getUserObj($_classRef);
                    $markers = $_procObj->postModifyMarkers($markers, $this);
                }
            }
            // send an email to each individual user, to ensure the
            // multilanguage version of the email
            $emailRecipients = array();
            // an array of language objects that are needed
            // for emails with different languages
            $languageObjects = array($GLOBALS['LANG']->lang => $GLOBALS['LANG']);
            // loop through each recipient and send the email
            foreach ($emails as $recipientData) {
                // don't send an email twice
                if (isset($emailRecipients[$recipientData['email']])) {
                    continue;
                }
                $emailSubject = $emailConfig['subject'];
                $emailMessage = $emailConfig['message'];
                $emailRecipients[$recipientData['email']] = $recipientData['email'];
                // check if the email needs to be localized
                // in the users' language
                if (GeneralUtility::isFirstPartOfStr($emailSubject, 'LLL:') || GeneralUtility::isFirstPartOfStr($emailMessage, 'LLL:')) {
                    $recipientLanguage = $recipientData['lang'] ? $recipientData['lang'] : 'default';
                    if (!isset($languageObjects[$recipientLanguage])) {
                        // a LANG object in this language hasn't been
                        // instantiated yet, so this is done here
                        /** @var $languageObject \TYPO3\CMS\Lang\LanguageService */
                        $languageObject = GeneralUtility::makeInstance(\TYPO3\CMS\Lang\LanguageService::class);
                        $languageObject->init($recipientLanguage);
                        $languageObjects[$recipientLanguage] = $languageObject;
                    } else {
                        $languageObject = $languageObjects[$recipientLanguage];
                    }
                    if (GeneralUtility::isFirstPartOfStr($emailSubject, 'LLL:')) {
                        $emailSubject = $languageObject->sL($emailSubject);
                    }
                    if (GeneralUtility::isFirstPartOfStr($emailMessage, 'LLL:')) {
                        $emailMessage = $languageObject->sL($emailMessage);
                    }
                }
                $emailSubject = \TYPO3\CMS\Core\Html\HtmlParser::substituteMarkerArray($emailSubject, $markers, '', TRUE, TRUE);
                $emailMessage = \TYPO3\CMS\Core\Html\HtmlParser::substituteMarkerArray($emailMessage, $markers, '', TRUE, TRUE);
                // Send an email to the recipient
                /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
                $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
                if (!empty($recipientData['realName'])) {
                    $recipient = array($recipientData['email'] => $recipientData['realName']);
                } else {
                    $recipient = $recipientData['email'];
                }
                $mail->setTo($recipient)->setSubject($emailSubject)->setFrom(\TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom())->setBody($emailMessage);
                $mail->send();
            }
            $emailRecipients = implode(',', $emailRecipients);
            $tcemainObj->newlog2('Notification email for stage change was sent to "' . $emailRecipients . '"', $table, $id);
        }
    }
 /**
  * Sets the sender of the mail message
  *
  * Mostly the sender is a combination of the name and the email address
  *
  * @return void
  */
 protected function setFrom()
 {
     $fromEmail = '';
     if ($this->typoScript['senderEmail']) {
         $fromEmail = $this->typoScript['senderEmail'];
     } elseif ($this->requestHandler->has($this->typoScript['senderEmailField'])) {
         $fromEmail = $this->requestHandler->get($this->typoScript['senderEmailField']);
     } else {
         $fromEmail = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'];
     }
     if (!\TYPO3\CMS\Core\Utility\GeneralUtility::validEmail($fromEmail)) {
         $fromEmail = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFromAddress();
     }
     $fromName = '';
     if ($this->typoScript['senderName']) {
         $fromName = $this->typoScript['senderName'];
     } elseif ($this->requestHandler->has($this->typoScript['senderNameField'])) {
         $fromName = $this->requestHandler->get($this->typoScript['senderNameField']);
     } else {
         $fromName = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName'];
     }
     $fromName = $this->sanitizeHeaderString($fromName);
     if (preg_match('/\\s|,/', $fromName) >= 1) {
         $fromName = '"' . $fromName . '"';
     }
     $from = array($fromEmail => $fromName);
     $this->mailMessage->setFrom($from);
 }
 /**
  * Sends a notification email, reporting system issues.
  *
  * @param Status[] $systemStatus Array of statuses
  * @return void
  */
 protected function sendNotificationEmail(array $systemStatus)
 {
     $systemIssues = array();
     foreach ($systemStatus as $statusProvider) {
         /** @var Status $status */
         foreach ($statusProvider as $status) {
             if ($status->getSeverity() > Status::OK) {
                 $systemIssues[] = (string) $status . CRLF . $status->getMessage() . CRLF . CRLF;
             }
         }
     }
     $notificationEmails = GeneralUtility::trimExplode(LF, $this->notificationEmail, true);
     $sendEmailsTo = array();
     foreach ($notificationEmails as $notificationEmail) {
         $sendEmailsTo[] = $notificationEmail;
     }
     $subject = sprintf($this->getLanguageService()->getLL('status_updateTask_email_subject'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']);
     $message = sprintf($this->getLanguageService()->getLL('status_problemNotification'), '', '');
     $message .= CRLF . CRLF;
     $message .= $this->getLanguageService()->getLL('status_updateTask_email_site') . ': ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
     $message .= CRLF . CRLF;
     $message .= $this->getLanguageService()->getLL('status_updateTask_email_issues') . ': ' . CRLF;
     $message .= implode(CRLF, $systemIssues);
     $message .= CRLF . CRLF;
     $from = MailUtility::getSystemFrom();
     /** @var MailMessage $mail */
     $mail = GeneralUtility::makeInstance(MailMessage::class);
     $mail->setFrom($from);
     $mail->setTo($sendEmailsTo);
     $mail->setSubject($subject);
     $mail->setBody($message);
     $mail->send();
 }
 /**
  * @param Model\Project $project
  * @param array         $receivers
  * @param bool          $isAccepted
  */
 public function updateStatusMail(Model\Project $project, array $receivers = [], $isAccepted = true)
 {
     $noReply = null;
     if ($this->settings['mail']['noReplyEmail'] && CoreUtility\GeneralUtility::validEmail($this->settings['mail']['noReplyEmail'])) {
         $noReply = [$this->settings['mail']['noReplyEmail'] => $this->settings['mail']['noReplyName'] ?: $this->settings['mail']['senderName']];
     }
     $carbonCopyReceivers = [];
     if ($this->settings['mail']['carbonCopy']) {
         foreach (explode(',', $this->settings['mail']['carbonCopy']) as $carbonCopyReceiver) {
             $tokens = CoreUtility\GeneralUtility::trimExplode(' ', $carbonCopyReceiver, true, 2);
             if (CoreUtility\GeneralUtility::validEmail($tokens[0])) {
                 $carbonCopyReceivers[$tokens[0]] = $tokens[1];
             }
         }
     }
     /** @var \TYPO3\CMS\Core\Mail\MailMessage $mailToSender */
     $mailToSender = CoreUtility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
     $mailToSender->setContentType('text/html');
     /**
      * Email to sender
      */
     $mailToSender->setFrom($noReply ?: CoreUtility\MailUtility::getSystemFrom())->setTo([$project->getRegistrant()->getEmail() => $project->getRegistrant()->getName()])->setCc($receivers)->setSubject(($this->settings['mail']['projectStatusUpdateSubject'] ?: (Lang::translate('mail_project_status_update_subject', $this->extensionName) ?: 'Project status update')) . " #{$project->getUid()}")->setBody($this->getStandAloneTemplate(CoreUtility\ExtensionManagementUtility::siteRelPath(CoreUtility\GeneralUtility::camelCaseToLowerCaseUnderscored($this->extensionName)) . 'Resources/Private/Templates/Email/ProjectStatusUpdated.html', ['settings' => $this->settings, 'project' => $project, 'accepted' => $isAccepted, 'addressees' => $this->getAddressees()]))->send();
 }
 /**
  * Breaking lines into fixed length lines, using MailUtility::breakLinesForEmail()
  *
  * @param	string		$str: The string to break
  * @param	string		$implChar: Line break character
  * @param	integer		$charWidth: Length of lines, default is $this->charWidth
  * @return	string		Processed string
  * @see MailUtility::breakLinesForEmail()
  */
 function breakLines($str, $implChar, $charWidth = 0)
 {
     $cW = $charWidth ? $charWidth : $this->charWidth;
     $linebreak = $implChar ? $implChar : $this->linebreak;
     return MailUtility::breakLinesForEmail($str, $linebreak, $cW);
 }
 /**
  * Sends a notification email
  *
  * @param  string     $recipients  comma-separated list of email addresses that should
  *                                 receive the notification
  * @param  array      $config      notification configuration
  * @param  object     $media       one or multiple media records (QueryResult)
  * @param  \Exception $exception   the exception that was thrown
  * @return boolean                 success status of email
  */
 protected function sendNotification($recipients, array $config, $media, \Exception $exception = NULL)
 {
     // Convert comma-separated list to array
     $recipients = array_map('trim', explode(',', $recipients));
     // Generate markers for the email subject and content
     $markers = array('###SIGNATURE###' => $config['signature']);
     if (isset($exception)) {
         $markers['###ERROR###'] = $exception->getMessage();
         $markers['###ERROR_FILE###'] = $exception->getFile();
         $markers['###ERROR_LINE###'] = $exception->getLine();
     }
     // Generate list of media files for the email
     $allMedia = $media instanceof Media ? array($media) : $media->toArray();
     $mediaFiles = array();
     foreach ($allMedia as $oneMedia) {
         // Get all properties of media record that can be outputted
         $mediaMarkers = array();
         foreach ($oneMedia->toArray() as $key => $value) {
             if (!is_object($value)) {
                 $mediaMarkers[$key] = $value;
             }
         }
         // Provide properties as markers
         $mediaFiles[] = $this->cObj->substituteMarkerArray($config['mediafiles'], $mediaMarkers, '###|###', TRUE);
     }
     $markers['###MEDIAFILES###'] = implode("\n", $mediaFiles);
     // Replace markers in subject and content
     $subject = $this->cObj->substituteMarkerArray($config['subject'], $markers);
     $message = $this->cObj->substituteMarkerArray($config['message'], $markers);
     // Send email
     return $this->objectManager->get('TYPO3\\CMS\\Core\\Mail\\MailMessage')->setFrom(\TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom())->setTo($recipients)->setSubject($subject)->setBody($message)->send();
 }
Example #14
0
 /**
  * Build and send warning email when new broken links were found
  *
  * @param string $pageSections Content of page section
  * @param array $modTsConfig TSconfig array
  * @return boolean TRUE if mail was sent, FALSE if or not
  * @throws \Exception if required modTsConfig settings are missing
  */
 protected function reportEmail($pageSections, array $modTsConfig)
 {
     $content = \TYPO3\CMS\Core\Html\HtmlParser::substituteSubpart($this->templateMail, '###PAGE_SECTION###', $pageSections);
     /** @var array $markerArray */
     $markerArray = array();
     /** @var array $validEmailList */
     $validEmailList = array();
     /** @var boolean $sendEmail */
     $sendEmail = TRUE;
     $markerArray['totalBrokenLink'] = $this->totalBrokenLink;
     $markerArray['totalBrokenLink_old'] = $this->oldTotalBrokenLink;
     // Hook
     if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['linkvalidator']['reportEmailMarkers'])) {
         foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['linkvalidator']['reportEmailMarkers'] as $userFunc) {
             $params = array('pObj' => &$this, 'markerArray' => $markerArray);
             $newMarkers = GeneralUtility::callUserFunction($userFunc, $params, $this);
             if (is_array($newMarkers)) {
                 $markerArray = GeneralUtility::array_merge($markerArray, $newMarkers);
             }
             unset($params);
         }
     }
     $content = \TYPO3\CMS\Core\Html\HtmlParser::substituteMarkerArray($content, $markerArray, '###|###', TRUE, TRUE);
     /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
     $mail = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
     if (empty($modTsConfig['mail.']['fromemail'])) {
         $modTsConfig['mail.']['fromemail'] = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFromAddress();
     }
     if (empty($modTsConfig['mail.']['fromname'])) {
         $modTsConfig['mail.']['fromname'] = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFromName();
     }
     if (GeneralUtility::validEmail($modTsConfig['mail.']['fromemail'])) {
         $mail->setFrom(array($modTsConfig['mail.']['fromemail'] => $modTsConfig['mail.']['fromname']));
     } else {
         throw new \Exception($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/Resources/Private/Language/locallang.xlf:tasks.error.invalidFromEmail'), '1295476760');
     }
     if (GeneralUtility::validEmail($modTsConfig['mail.']['replytoemail'])) {
         $mail->setReplyTo(array($modTsConfig['mail.']['replytoemail'] => $modTsConfig['mail.']['replytoname']));
     }
     if (!empty($modTsConfig['mail.']['subject'])) {
         $mail->setSubject($modTsConfig['mail.']['subject']);
     } else {
         throw new \Exception($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/Resources/Private/Language/locallang.xlf:tasks.error.noSubject'), '1295476808');
     }
     if (!empty($this->email)) {
         $emailList = GeneralUtility::trimExplode(',', $this->email);
         foreach ($emailList as $emailAdd) {
             if (!GeneralUtility::validEmail($emailAdd)) {
                 throw new \Exception($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/Resources/Private/Language/locallang.xlf:tasks.error.invalidToEmail'), '1295476821');
             } else {
                 $validEmailList[] = $emailAdd;
             }
         }
     }
     if (is_array($validEmailList) && !empty($validEmailList)) {
         $mail->setTo($validEmailList);
     } else {
         $sendEmail = FALSE;
     }
     if ($sendEmail) {
         $mail->setBody($content, 'text/html');
         $mail->send();
     }
     return $sendEmail;
 }
 /**
  * @param  array  $msg
  * @return string
  */
 public function mailAction(array $msg = array())
 {
     $recipient = $this->widgetConfiguration['recipient'];
     $sender = $this->widgetConfiguration['sender'];
     $required = $this->widgetConfiguration['required'];
     $missing = array();
     /* example: $required = [ 'name', 'email,phone' ] => name and (phone or email) are required.*/
     foreach ($required as $orFieldList) {
         $orFields = explode(',', $orFieldList);
         $found = false;
         foreach ($orFields as $field) {
             if (array_key_exists($field, $msg) && strlen($msg[$field]) != 0) {
                 $found = true;
                 break;
             }
         }
         if (!$found) {
             foreach ($orFields as $field) {
                 $missing[] = $field;
             }
         }
     }
     if (count($missing)) {
         return json_encode(array('status' => 'fields-missing', 'missing' => $missing));
     }
     if (!is_array($recipient) || !array_key_exists('email', $recipient)) {
         /* TODO: Throw exception instead. */
         return json_encode(array('status' => 'internal-error', 'error' => '$recipient is not valid'));
     }
     if (isset($recipient['name']) && strlen($recipient['name']) > 0) {
         $tmp = $recipient;
         $recipient = array();
         foreach (GeneralUtility::trimExplode(',', $tmp['email']) as $email) {
             $recipient[$email] = $tmp['name'];
         }
     } else {
         $recipient = GeneralUtility::trimExplode(',', $recipient['email']);
     }
     $sender = $sender !== null ? array($sender['email'] => $sender['name']) : MailUtility::getSystemFrom();
     $recipientSave = $recipient;
     $recipientOverwrite = $this->widgetConfiguration['receiver_overwrite_email'];
     if ($recipientOverwrite !== null) {
         $recipient = $recipientOverwrite;
     }
     $params = array('to' => $recipient, 'from' => $sender, 'msg' => $msg);
     $view = GeneralUtility::makeInstance('TYPO3\\CMS\\Fluid\\View\\StandaloneView');
     $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName($this->widgetConfiguration['mailTemplate']));
     $view->assignMultiple($params);
     $text = $view->render();
     list($subject, $body) = explode("\n", $text, 2);
     if ($recipientOverwrite !== null) {
         $subject .= ' – Recipient: ' . implode(',', $recipientSave);
     }
     $mail = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
     $mail->setFrom($sender);
     $mail->setTo($recipient);
     $mail->setSubject($subject);
     $mail->setBody(trim($body));
     if (isset($msg['email']) && strlen($msg['email']) > 0) {
         $mail->setReplyTo($msg['email']);
     }
     $mail->send();
     return json_encode(array('status' => 'ok'));
 }
Example #16
0
 /**
  * Breaking lines into fixed length lines, using GeneralUtility::breakLinesForEmail()
  *
  * @param string $content The string to break
  * @param array $conf Configuration options: linebreak, charWidth; stdWrap enabled
  *
  * @return string Processed string
  * @see GeneralUtility::breakLinesForEmail()
  */
 public function breakLines($content, array $conf)
 {
     $linebreak = $GLOBALS['TSFE']->cObj->stdWrap($conf['linebreak'] ? $conf['linebreak'] : chr(32) . LF, $conf['linebreak.']);
     $charWidth = $GLOBALS['TSFE']->cObj->stdWrap($conf['charWidth'] ? intval($conf['charWidth']) : 76, $conf['charWidth.']);
     return MailUtility::breakLinesForEmail($content, $linebreak, $charWidth);
 }
Example #17
0
 /**
  * @param string $templateName
  * @param array $sender
  * @return bool|array
  */
 protected function cleanSender($templateName, array $sender = NULL)
 {
     if ($sender) {
         return $sender;
     }
     if (isset($this->settings['templates'][$templateName]) && isset($this->settings['templates'][$templateName]['sender'])) {
         $senderInfo = $this->settings['templates'][$templateName]['sender'];
         return array($senderInfo['email'] => $senderInfo['name']);
     }
     if ($this->hasDefaultSender()) {
         return $this->defaultSender;
     }
     $systemDefault = MailUtility::getSystemFrom();
     if ($systemDefault) {
         return $systemDefault;
     }
     return FALSE;
 }
 /**
  * action create
  *
  * @param News $newNews
  * @param string $link
  * @return void
  */
 public function createAction(News $newNews, $link = '')
 {
     $newNews->setDatetime(new \DateTime());
     if (empty($this->settings['enableNewItemsByDefault'])) {
         $newNews->setHidden(1);
     }
     if ($link !== '') {
         $linkObject = new \Tx_News_Domain_Model_Link();
         $linkObject->setUri($link);
         $linkObject->setTitle($link);
         $newNews->addRelatedLink($linkObject);
     }
     // save news
     $this->newsRepository->add($newNews);
     $this->addFlashMessage(LocalizationUtility::translate('news.created', $this->extensionName));
     // send mail
     if ($this->settings['recipientMail']) {
         /** @var $message \TYPO3\CMS\Core\Mail\MailMessage */
         $message = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
         $from = MailUtility::getSystemFrom();
         $message->setFrom($from)->setTo(array($this->settings['recipientMail'] => 'News Manager'))->setSubject('[New News] ' . $newNews->getTitle())->setBody('<h1>New News</h1>' . $newNews->getBodytext(), 'text/html')->send();
     }
     // clear page cache after save
     if (!$newNews->getHidden()) {
         $this->flushNewsCache($newNews);
     }
     // go to thank you action
     $this->redirect('thankyou');
 }
 /**
  * Will send an email notification to warning_email_address/the login users email address when a login session is just started.
  * Depends on various parameters whether mails are send and to whom.
  *
  * @return void
  * @access private
  */
 private function emailAtLogin()
 {
     if ($this->loginSessionStarted) {
         // Send notify-mail
         $subject = 'At "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '"' . ' from ' . GeneralUtility::getIndpEnv('REMOTE_ADDR') . (GeneralUtility::getIndpEnv('REMOTE_HOST') ? ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')' : '');
         $msg = sprintf('User "%s" logged in from %s (%s) at "%s" (%s)', $this->user['username'], GeneralUtility::getIndpEnv('REMOTE_ADDR'), GeneralUtility::getIndpEnv('REMOTE_HOST'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'], GeneralUtility::getIndpEnv('HTTP_HOST'));
         // Warning email address
         if ($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr']) {
             $warn = 0;
             $prefix = '';
             if ((int) $GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode'] & 1) {
                 // first bit: All logins
                 $warn = 1;
                 $prefix = $this->isAdmin() ? '[AdminLoginWarning]' : '[LoginWarning]';
             }
             if ($this->isAdmin() && (int) $GLOBALS['TYPO3_CONF_VARS']['BE']['warning_mode'] & 2) {
                 // second bit: Only admin-logins
                 $warn = 1;
                 $prefix = '[AdminLoginWarning]';
             }
             if ($warn) {
                 $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
                 /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
                 $mail = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
                 $mail->setTo($GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'])->setFrom($from)->setSubject($prefix . ' ' . $subject)->setBody($msg);
                 $mail->send();
             }
         }
         // If An email should be sent to the current user, do that:
         if ($this->uc['emailMeAtLogin'] && strstr($this->user['email'], '@')) {
             $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
             /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
             $mail = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
             $mail->setTo($this->user['email'])->setFrom($from)->setSubject($subject)->setBody($msg);
             $mail->send();
         }
     }
 }
 /**
  * @test
  */
 public function breakLinesForEmailBreaksTextWithNoSpaceFoundBeforeLimit()
 {
     $newlineChar = LF;
     $lineWidth = 10;
     // first space after 20 chars (more than $lineWidth)
     $str = 'abcdefghijklmnopqrst uvwxyz 123456';
     $returnString = \TYPO3\CMS\Core\Utility\MailUtility::breakLinesForEmail($str, $newlineChar, $lineWidth);
     $this->assertEquals($returnString, 'abcdefghijklmnopqrst' . LF . 'uvwxyz' . LF . '123456');
 }
 /**
  * Sends a notification email
  *
  * @param string $message The message content. If blank, no email is sent.
  * @param string $recipients Comma list of recipient email addresses
  * @param string $cc Email address of recipient of an extra mail. The same mail will be sent ONCE more; not using a CC header but sending twice.
  * @param string $senderAddress "From" email address
  * @param string $senderName Optional "From" name
  * @param string $replyTo Optional "Reply-To" header email address.
  * @return boolean Returns TRUE if sent
  */
 public function sendNotifyEmail($message, $recipients, $cc, $senderAddress, $senderName = '', $replyTo = '')
 {
     $result = FALSE;
     /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
     $mail = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
     $senderName = trim($senderName);
     $senderAddress = trim($senderAddress);
     if ($senderName !== '' && $senderAddress !== '') {
         $sender = array($senderAddress => $senderName);
     } elseif ($senderAddress !== '') {
         $sender = array($senderAddress);
     } else {
         $sender = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
     }
     $mail->setFrom($sender);
     $parsedReplyTo = \TYPO3\CMS\Core\Utility\MailUtility::parseAddresses($replyTo);
     if (count($parsedReplyTo) > 0) {
         $mail->setReplyTo($parsedReplyTo);
     }
     $message = trim($message);
     if ($message !== '') {
         // First line is subject
         $messageParts = explode(LF, $message, 2);
         $subject = trim($messageParts[0]);
         $plainMessage = trim($messageParts[1]);
         $parsedRecipients = \TYPO3\CMS\Core\Utility\MailUtility::parseAddresses($recipients);
         if (count($parsedRecipients) > 0) {
             $mail->setTo($parsedRecipients)->setSubject($subject)->setBody($plainMessage);
             $mail->send();
         }
         $parsedCc = \TYPO3\CMS\Core\Utility\MailUtility::parseAddresses($cc);
         if (count($parsedCc) > 0) {
             /** @var $mail \TYPO3\CMS\Core\Mail\MailMessage */
             $mail = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
             if (count($parsedReplyTo) > 0) {
                 $mail->setReplyTo($parsedReplyTo);
             }
             $mail->setFrom($sender)->setTo($parsedCc)->setSubject($subject)->setBody($plainMessage);
             $mail->send();
         }
         $result = TRUE;
     }
     return $result;
 }
Example #22
0
 /**
  * Breaking lines into fixed length lines, using GeneralUtility::breakLinesForEmail()
  *
  * @param        string  $str       : The string to break
  * @param        string  $implChar  : Line break character
  * @param        integer $charWidth : Length of lines, default is $this->charWidth
  *
  * @return        string                Processed string
  */
 function breakLines($str, $implChar = LF, $charWidth = FALSE)
 {
     $charWidth = $charWidth === FALSE ? Configuration::getPlainTextWith() : (int) $charWidth;
     return MailUtility::breakLinesForEmail($str, $implChar, $charWidth);
 }
Example #23
0
 /**
  * Sets the sender of the mail message
  *
  * Mostly the sender is a combination of the name and the email address
  *
  * @return void
  */
 protected function setFrom()
 {
     if (isset($this->typoScript['senderEmail'])) {
         $fromEmail = $this->formUtility->renderItem($this->typoScript['senderEmail.'], $this->typoScript['senderEmail']);
     } elseif ($this->getTypoScriptValueFromIncomingData('senderEmailField') !== null) {
         $fromEmail = $this->getTypoScriptValueFromIncomingData('senderEmailField');
     } else {
         $fromEmail = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'];
     }
     if (!GeneralUtility::validEmail($fromEmail)) {
         $fromEmail = MailUtility::getSystemFromAddress();
     }
     if (isset($this->typoScript['senderName'])) {
         $fromName = $this->formUtility->renderItem($this->typoScript['senderName.'], $this->typoScript['senderName']);
     } elseif ($this->getTypoScriptValueFromIncomingData('senderNameField') !== null) {
         $fromName = $this->getTypoScriptValueFromIncomingData('senderNameField');
     } else {
         $fromName = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName'];
     }
     $fromName = $this->sanitizeHeaderString($fromName);
     if (!empty($fromName)) {
         $from = array($fromEmail => $fromName);
     } else {
         $from = $fromEmail;
     }
     $this->mailMessage->setFrom($from);
 }
Example #24
0
 /**
  * This is the main-function for sending Mails
  *
  * @param array $mailTo
  * @param array $mailFrom
  * @param string $subject
  * @param string $emailBody
  *
  * @return integer the number of recipients who were accepted for delivery
  */
 public function send($mailTo, $mailFrom, $subject, $emailBody)
 {
     if (!($mailTo && is_array($mailTo) && GeneralUtility::validEmail(key($mailTo)))) {
         $this->log->error('Given mailto email address is invalid.', $mailTo);
         return FALSE;
     }
     if (!($mailFrom && is_array($mailFrom) && GeneralUtility::validEmail(key($mailFrom)))) {
         $mailFrom = MailUtility::getSystemFrom();
     }
     /* @var $message \TYPO3\CMS\Core\Mail\MailMessage */
     $message = $this->objectManager->get('TYPO3\\CMS\\Core\\Mail\\MailMessage');
     $message->setTo($mailTo)->setFrom($mailFrom)->setSubject($subject)->setCharset(\TYPO3\T3extblog\Utility\GeneralUtility::getTsFe()->metaCharset);
     // send text or html emails
     if (strip_tags($emailBody) === $emailBody) {
         $message->setBody($emailBody, 'text/plain');
     } else {
         $message->setBody($emailBody, 'text/html');
     }
     if (!$this->settings['debug']['disableEmailTransmission']) {
         $message->send();
     }
     $logData = array('mailTo' => $mailTo, 'mailFrom' => $mailFrom, 'subject' => $subject, 'emailBody' => $emailBody, 'isSent' => $message->isSent());
     $this->log->dev('Email sent.', $logData);
     return $logData['isSent'];
 }
 /**
  * Sends a notification email, reporting system issues.
  *
  * @param array $systemStatus Array of statuses
  */
 protected function sendNotificationEmail(array $systemStatus)
 {
     $systemIssues = array();
     foreach ($systemStatus as $statusProvider) {
         foreach ($statusProvider as $status) {
             if ($status->getSeverity() > \TYPO3\CMS\Reports\Report\Status\Status::OK) {
                 $systemIssues[] = (string) $status;
             }
         }
     }
     $subject = sprintf($GLOBALS['LANG']->getLL('status_updateTask_email_subject'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']);
     $message = sprintf($GLOBALS['LANG']->getLL('status_problemNotification'), '', '');
     $message .= CRLF . CRLF;
     $message .= $GLOBALS['LANG']->getLL('status_updateTask_email_site') . ': ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
     $message .= CRLF . CRLF;
     $message .= $GLOBALS['LANG']->getLL('status_updateTask_email_issues') . ': ' . CRLF;
     $message .= implode(CRLF, $systemIssues);
     $message .= CRLF . CRLF;
     $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
     $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
     $mail->setFrom($from);
     $mail->setTo($this->notificationEmail);
     $mail->setSubject($subject);
     $mail->setBody($message);
     $mail->send();
 }
Example #26
0
 /**
  * @test
  * @dataProvider parseAddressesProvider
  */
 public function parseAddressesTest($source, $addressList)
 {
     $returnArray = \TYPO3\CMS\Core\Utility\MailUtility::parseAddresses($source);
     $this->assertEquals($addressList, $returnArray);
 }
 /**
  * Sends a notification email
  *
  * @param string $message The message content. If blank, no email is sent.
  * @param string $recipients Comma list of recipient email addresses
  * @param string $cc Email address of recipient of an extra mail. The same mail will be sent ONCE more; not using a CC header but sending twice.
  * @param string $senderAddress "From" email address
  * @param string $senderName Optional "From" name
  * @param string $replyTo Optional "Reply-To" header email address.
  * @return bool Returns TRUE if sent
  */
 public function sendNotifyEmail($message, $recipients, $cc, $senderAddress, $senderName = '', $replyTo = '')
 {
     /** @var $mail MailMessage */
     $mail = GeneralUtility::makeInstance(MailMessage::class);
     $senderName = trim($senderName);
     $senderAddress = trim($senderAddress);
     if ($senderName !== '' && $senderAddress !== '') {
         $sender = array($senderAddress => $senderName);
     } elseif ($senderAddress !== '') {
         $sender = array($senderAddress);
     } else {
         $sender = MailUtility::getSystemFrom();
     }
     $mail->setFrom($sender);
     $parsedReplyTo = MailUtility::parseAddresses($replyTo);
     if (!empty($parsedReplyTo)) {
         $mail->setReplyTo($parsedReplyTo);
     }
     $message = trim($message);
     if ($message !== '') {
         // First line is subject
         $messageParts = explode(LF, $message, 2);
         $subject = trim($messageParts[0]);
         $plainMessage = trim($messageParts[1]);
         $parsedRecipients = MailUtility::parseAddresses($recipients);
         if (!empty($parsedRecipients)) {
             $mail->setTo($parsedRecipients)->setSubject($subject)->setBody($plainMessage);
             $mail->send();
         }
         $parsedCc = MailUtility::parseAddresses($cc);
         if (!empty($parsedCc)) {
             /** @var $mail MailMessage */
             $mail = GeneralUtility::makeInstance(MailMessage::class);
             if (!empty($parsedReplyTo)) {
                 $mail->setReplyTo($parsedReplyTo);
             }
             $mail->setFrom($sender)->setTo($parsedCc)->setSubject($subject)->setBody($plainMessage);
             $mail->send();
         }
         return true;
     }
     return false;
 }
 /**
  * Create a new Message.
  *
  * Details may be optionally passed into the constructor.
  *
  * @param string $subject
  * @param string $body
  * @param string $contentType
  * @param string $charset
  */
 public function __construct($subject = null, $body = null, $contentType = null, $charset = null)
 {
     parent::__construct($subject, $body, $contentType, $charset);
     $this->setFrom(MailUtility::getSystemFrom());
 }
 /**
  * Start function
  * This class is able to generate a mail in formmail-style from the data in $V
  * Fields:
  *
  * [recipient]:			email-adress of the one to receive the mail. If array, then all values are expected to be recipients
  * [attachment]:		....
  *
  * [subject]:			The subject of the mail
  * [from_email]:		Sender email. If not set, [email] is used
  * [from_name]:			Sender name. If not set, [name] is used
  * [replyto_email]:		Reply-to email. If not set [from_email] is used
  * [replyto_name]:		Reply-to name. If not set [from_name] is used
  * [organisation]:		Organization (header)
  * [priority]:			Priority, 1-5, default 3
  * [html_enabled]:		If mail is sent as html
  * [use_base64]:		If set, base64 encoding will be used instead of quoted-printable
  *
  * @param array $valueList Contains values for the field names listed above (with slashes removed if from POST input)
  * @param boolean $base64 Whether to base64 encode the mail content
  * @return void
  * @todo Define visibility
  */
 public function start($valueList, $base64 = FALSE)
 {
     $this->mailMessage = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
     if ($GLOBALS['TSFE']->config['config']['formMailCharset']) {
         // Respect formMailCharset if it was set
         $this->characterSet = $GLOBALS['TSFE']->csConvObj->parse_charset($GLOBALS['TSFE']->config['config']['formMailCharset']);
     } elseif ($GLOBALS['TSFE']->metaCharset != $GLOBALS['TSFE']->renderCharset) {
         // Use metaCharset for mail if different from renderCharset
         $this->characterSet = $GLOBALS['TSFE']->metaCharset;
     } else {
         // Otherwise use renderCharset as default
         $this->characterSet = $GLOBALS['TSFE']->renderCharset;
     }
     if ($base64 || $valueList['use_base64']) {
         $this->encoding = 'base64';
     }
     if (isset($valueList['recipient'])) {
         // Convert form data from renderCharset to mail charset
         $this->subject = $valueList['subject'] ? $valueList['subject'] : 'Formmail on ' . \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('HTTP_HOST');
         $this->subject = $this->sanitizeHeaderString($this->subject);
         $this->fromName = $valueList['from_name'] ? $valueList['from_name'] : ($valueList['name'] ? $valueList['name'] : '');
         $this->fromName = $this->sanitizeHeaderString($this->fromName);
         $this->replyToName = $valueList['replyto_name'] ? $valueList['replyto_name'] : $this->fromName;
         $this->replyToName = $this->sanitizeHeaderString($this->replyToName);
         $this->organisation = $valueList['organisation'] ? $valueList['organisation'] : '';
         $this->organisation = $this->sanitizeHeaderString($this->organisation);
         $this->fromAddress = $valueList['from_email'] ? $valueList['from_email'] : ($valueList['email'] ? $valueList['email'] : '');
         if (!\TYPO3\CMS\Core\Utility\GeneralUtility::validEmail($this->fromAddress)) {
             $this->fromAddress = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFromAddress();
             $this->fromName = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFromName();
         }
         $this->replyToAddress = $valueList['replyto_email'] ? $valueList['replyto_email'] : $this->fromAddress;
         $this->priority = $valueList['priority'] ? \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($valueList['priority'], 1, 5) : 3;
         // Auto responder
         $this->autoRespondMessage = trim($valueList['auto_respond_msg']) && $this->fromAddress ? trim($valueList['auto_respond_msg']) : '';
         if ($this->autoRespondMessage !== '') {
             // Check if the value of the auto responder message has been modified with evil intentions
             $autoRespondChecksum = $valueList['auto_respond_checksum'];
             $correctHmacChecksum = \TYPO3\CMS\Core\Utility\GeneralUtility::hmac($this->autoRespondMessage);
             if ($autoRespondChecksum !== $correctHmacChecksum) {
                 \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog('Possible misuse of t3lib_formmail auto respond method. Subject: ' . $valueList['subject'], 'Core', \TYPO3\CMS\Core\Utility\GeneralUtility::SYSLOG_SEVERITY_ERROR);
                 return;
             } else {
                 $this->autoRespondMessage = $this->sanitizeHeaderString($this->autoRespondMessage);
             }
         }
         $plainTextContent = '';
         $htmlContent = '<table border="0" cellpadding="2" cellspacing="2">';
         // Runs through $V and generates the mail
         if (is_array($valueList)) {
             foreach ($valueList as $key => $val) {
                 if (!\TYPO3\CMS\Core\Utility\GeneralUtility::inList($this->reserved_names, $key)) {
                     $space = strlen($val) > 60 ? LF : '';
                     $val = is_array($val) ? implode($val, LF) : $val;
                     // Convert form data from renderCharset to mail charset (HTML may use entities)
                     $plainTextValue = $val;
                     $HtmlValue = htmlspecialchars($val);
                     $plainTextContent .= strtoupper($key) . ':  ' . $space . $plainTextValue . LF . $space;
                     $htmlContent .= '<tr><td bgcolor="#eeeeee"><font face="Verdana" size="1"><strong>' . strtoupper($key) . '</strong></font></td><td bgcolor="#eeeeee"><font face="Verdana" size="1">' . nl2br($HtmlValue) . '&nbsp;</font></td></tr>';
                 }
             }
         }
         $htmlContent .= '</table>';
         $this->plainContent = $plainTextContent;
         if ($valueList['html_enabled']) {
             $this->mailMessage->setBody($htmlContent, 'text/html', $this->characterSet);
             $this->mailMessage->addPart($plainTextContent, 'text/plain', $this->characterSet);
         } else {
             $this->mailMessage->setBody($plainTextContent, 'text/plain', $this->characterSet);
         }
         for ($a = 0; $a < 10; $a++) {
             $variableName = 'attachment' . ($a ? $a : '');
             if (!isset($_FILES[$variableName])) {
                 continue;
             }
             if (!is_uploaded_file($_FILES[$variableName]['tmp_name'])) {
                 \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog('Possible abuse of t3lib_formmail: temporary file "' . $_FILES[$variableName]['tmp_name'] . '" ("' . $_FILES[$variableName]['name'] . '") was not an uploaded file.', 'Core', \TYPO3\CMS\Core\Utility\GeneralUtility::SYSLOG_SEVERITY_ERROR);
             }
             if ($_FILES[$variableName]['tmp_name']['error'] !== UPLOAD_ERR_OK) {
                 \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog('Error in uploaded file in t3lib_formmail: temporary file "' . $_FILES[$variableName]['tmp_name'] . '" ("' . $_FILES[$variableName]['name'] . '") Error code: ' . $_FILES[$variableName]['tmp_name']['error'], 'Core', \TYPO3\CMS\Core\Utility\GeneralUtility::SYSLOG_SEVERITY_ERROR);
             }
             $theFile = \TYPO3\CMS\Core\Utility\GeneralUtility::upload_to_tempfile($_FILES[$variableName]['tmp_name']);
             $theName = $_FILES[$variableName]['name'];
             if ($theFile && file_exists($theFile)) {
                 if (filesize($theFile) < $GLOBALS['TYPO3_CONF_VARS']['FE']['formmailMaxAttachmentSize']) {
                     $this->mailMessage->attach(Swift_Attachment::fromPath($theFile)->setFilename($theName));
                 }
             }
             $this->temporaryFiles[] = $theFile;
         }
         $from = $this->fromName ? array($this->fromAddress => $this->fromName) : array($this->fromAddress);
         $this->recipient = $this->parseAddresses($valueList['recipient']);
         $this->mailMessage->setSubject($this->subject)->setFrom($from)->setTo($this->recipient)->setPriority($this->priority);
         $replyTo = $this->replyToName ? array($this->replyToAddress => $this->replyToName) : array($this->replyToAddress);
         $this->mailMessage->setReplyTo($replyTo);
         $this->mailMessage->getHeaders()->addTextHeader('Organization', $this->organisation);
         if ($valueList['recipient_copy']) {
             $this->mailMessage->setCc($this->parseAddresses($valueList['recipient_copy']));
         }
         $this->mailMessage->setCharset($this->characterSet);
         // Ignore target encoding. This is handled automatically by Swift Mailer and overriding the defaults
         // is not worth the trouble
         // Log dirty header lines
         if ($this->dirtyHeaders) {
             \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog('Possible misuse of t3lib_formmail: see TYPO3 devLog', 'Core', \TYPO3\CMS\Core\Utility\GeneralUtility::SYSLOG_SEVERITY_ERROR);
             if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']) {
                 \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('t3lib_formmail: ' . \TYPO3\CMS\Core\Utility\GeneralUtility::arrayToLogString($this->dirtyHeaders, '', 200), 'Core', 3);
             }
         }
     }
 }
 /**
  * Notifies participants for the next event
  *
  * @return void
  */
 public function notifyCommand()
 {
     $this->settings = $this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS);
     $eventStartTime = $this->settings['eventStartTime'];
     $participantGroupId = $this->settings['participantGroupId'];
     $eventPageUid = $this->settings['eventPageUid'];
     $offset = 0;
     $eventStartDate = $this->div->nextEventDate($offset);
     $events = $this->eventRepository->findByStart($eventStartDate->format("Y-m-d H:i:s"));
     if ($events->count() == 0) {
         $this->div->createEvent($eventStartDate);
         $events = $this->eventRepository->findByStart($eventStartDate->format("Y-m-d H:i:s"));
     }
     if ($events->getFirst()->getActive()) {
         $this->initFrontend();
         $cObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\ContentObject\\ContentObjectRenderer');
         $link = $cObj->typolink_URL(array('parameter' => "{$eventPageUid}", 'forceAbsoluteUrl' => 1));
         $acceptUrl = $link . "?&tx_pceventscheduler_pceventscheduler%5Baction%5D=accept";
         $cancelUrl = $link . "?&tx_pceventscheduler_pceventscheduler%5Baction%5D=cancel";
         $participantsUnknown = $this->participantRepository->findParticipantsUnknown($events->getFirst()->getUid(), $participantGroupId);
         if (isset($participantsUnknown)) {
             foreach ($participantsUnknown as $participantUnknown) {
                 $receiverEmail = $participantUnknown['email'];
                 $receiverName = $participantUnknown['name'];
                 $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
                 $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
                 $mail->setFrom($from);
                 $mail->setSubject($this->settings['notifyMailSubject']);
                 $mail->setTo($receiverEmail);
                 $mail->setBody(str_replace(array('###name###', '###eventdate###', '###eventtime###', '###eventlocation###', '###acceptlink###', '###cancellink###'), array($receiverName, $events->getFirst()->getStart()->format("d.m.Y"), $eventStartTime, $events->getFirst()->getLocation(), $acceptUrl, $cancelUrl), $this->settings['notifyMailBody']), 'text/html');
                 $mail->send();
             }
         }
     }
     return true;
 }