/** * Compose the email data to be sent. * * @param FormConfig $formConfig * @param EmailConfig $emailConfig * @param FormData $formData */ private function emailCompose(FormConfig $formConfig, EmailConfig $emailConfig, FormData $formData) { /* * Create message object */ $this->message = \Swift_Message::newInstance(); $this->message->setEncoder(\Swift_Encoding::get8BitEncoding()); // Set our Twig lookup path $this->addTwigPath(); // If the form has it's own templates defined, use those, else the globals. $templateSubject = $formConfig->getTemplates()->getSubject() ?: $this->config['templates']['subject']; $templateEmail = $formConfig->getTemplates()->getEmail() ?: $this->config['templates']['email']; $fieldmap = $this->config['fieldmap']['email']; /* * Subject */ $html = $this->app['render']->render($templateSubject, array($fieldmap['subject'] => $formConfig->getNotification()->getSubject(), $fieldmap['config'] => $emailConfig, $fieldmap['data'] => $formData)); $subject = new \Twig_Markup($html, 'UTF-8'); /* * Body */ $html = $this->app['render']->render($templateEmail, array($fieldmap['fields'] => $formConfig->getFields(), $fieldmap['config'] => $emailConfig, $fieldmap['data'] => $this->getBodyData($emailConfig, $formData))); $body = new \Twig_Markup($html, 'UTF-8'); $text = preg_replace('/<style\\b[^>]*>(.*?)<\\/style>/s', '', $body); /* * Build email */ $this->message->setSubject($subject)->setBody(strip_tags($text))->addPart($body, 'text/html'); }
public function processAction(Request $request, $id, $type) { // Form options $options = array(); /** @var User $user */ $user = $this->getDoctrine()->getRepository(self::NAMESPACED_CLASS)->findOneBy(array('userId' => $id)); if (!$user) { // define form for each role if ($type == 1) { $role = 'ROLE_FRIEND'; } else { $role = 'ROLE_ACTIVE'; } $class = self::NAMESPACED_CLASS; // PHP quirk. $user = new $class(); $options['mode'] = 'new'; $options['role'] = $role; $user->setRole($role); } else { $options['mode'] = 'edit'; $options['role'] = $user->getRole(); $user->setBirthDate($user->getBirthDate()->format('Y-m-d')); } $formType = self::NAMESPACED_FORM_TYPE; // PHP quirk. $form = $this->createForm(new $formType(), $user, $options); // Check if form was submitted $form->handleRequest($request); // Check form validation if ($form->isValid()) { // Clean date $birthDate = new \DateTime($user->getBirthDate()); $user->setBirthDate($birthDate); $em = $this->getDoctrine()->getManager(); ## Extend the default form validation if ($user->getUserId() <= 0) { if ($user->getRole() == 'ROLE_ACTIVE') { $user->setIsActive(0); // Build message object $message = \Swift_Message::newInstance()->setEncoder(\Swift_Encoding::get8BitEncoding())->setSubject('Nuevo Usuario Activo')->setFrom('*****@*****.**')->setTo('*****@*****.**')->setBody($this->renderView('TecAytPortalBundle:Email:new.html.twig', array('user' => $user)), 'text/html'); $mailer = $this->get('mailer'); $mailer->send($message); } // Load security encoder $factory = $this->get('security.encoder_factory'); /* @var \Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface $encoder */ $encoder = $factory->getEncoder($user); $encodedPassword = $encoder->encodePassword($user->getPassword(), $user->getSalt()); $user->setPassword($encodedPassword); $em->persist($user); } // Persist to database using Entity Manager $em->flush(); return $this->redirect($this->generateUrl('tec_ayt_portal_user_profile', array('id' => $user->getUserId()))); } // Render as new Entity return $this->render('TecAytPortalBundle:User:form.html.twig', array('form' => $form->createView())); }
public function testGet8BitEncodingReturns8BitEncoder() { $encoder = Swift_Encoding::get8BitEncoding(); $this->assertEqual('8bit', $encoder->getName()); }
/** * Le contenu du message (email,sujet,contenu,...) * @param string $subject * @param array|string $from * @param array|string $recipient * @param string $bodyhtml * @param bool $setReadReceiptTo * @internal param void $sw_message * @internal param string $bodytxt * @return \Swift_Mime_Message * @access public * @static */ public function body_mail($subject, $from = array(), $recipient = array(), $bodyhtml, $setReadReceiptTo = false) { $sw_message = Swift_Message::newInstance(); $sw_message->getHeaders()->get('Content-Type')->setValue('text/html'); $sw_message->getHeaders()->get('Content-Type')->setParameter('charset', 'utf-8'); $sw_message->setSubject($subject)->setEncoder(Swift_Encoding::get8BitEncoding())->setFrom($from)->setTo($recipient)->setBody($bodyhtml, 'text/html')->addPart(magixcjquery_form_helpersforms::inputTagClean($bodyhtml), 'text/plain'); if ($setReadReceiptTo) { $sw_message->setReadReceiptTo($setReadReceiptTo); } return $sw_message; }
/** * Invokes the HTML mailing class * Example for $mailconf. * * $mailconf = array( * 'plain' => Array ( * 'content'=> '' // plain content as string * ), * 'html' => Array ( * 'content'=> '', // html content as string * 'path' => '', * 'useHtml' => '' // is set mail is send as multipart * ), * 'defaultCharset' => 'utf-8', // your chartset * 'encoding' => '8-bit', // your encoding * 'attach' => Array (), // your attachment as array * 'alternateSubject' => '', // is subject empty will be ste alternateSubject * 'recipient' => '', // comma seperate list of recipient * 'recipient_copy' => '', // bcc * 'fromEmail' => '', // fromMail * 'fromName' => '', // fromName * 'replyTo' => '', // replyTo * 'priority' => '3', // priority of your Mail * 1 = highest, * 5 = lowest, * 3 = normal * ); * * @param array $mailconf Configuration for the mailerengine * * @return bool */ public static function sendMail(array $mailconf) { $hooks = \CommerceTeam\Commerce\Factory\HookFactory::getHooks('Utility/GeneralUtility', 'sendMail'); $additionalData = array(); if ($mailconf['additionalData']) { $additionalData = $mailconf['additionalData']; } foreach ($hooks as $hookObj) { // this is the current hook if (method_exists($hookObj, 'preProcessMail')) { $hookObj->preProcessMail($mailconf, $additionalData); } } foreach ($hooks as $hookObj) { if (method_exists($hookObj, 'ownMailRendering')) { return $hookObj->ownMailRendering($mailconf, $additionalData, $hooks); } } // validate e-mail addesses $mailconf['recipient'] = self::validEmailList($mailconf['recipient']); if ($mailconf['recipient']) { $parts = preg_split('/<title>|<\\/title>/i', $mailconf['html']['content'], 3); if (trim($parts[1])) { $subject = strip_tags(trim($parts[1])); } elseif ($mailconf['plain']['subject']) { $subject = $mailconf['plain']['subject']; } else { $subject = $mailconf['alternateSubject']; } /** * Mail message. * * @var \TYPO3\CMS\Core\Mail\MailMessage */ $message = CoreGeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage'); $message->setCharset($mailconf['defaultCharset']); if ($mailconf['encoding'] == 'base64') { $message->setEncoder(\Swift_Encoding::getBase64Encoding()); } elseif ($mailconf['encoding'] == '8bit') { $message->setEncoder(\Swift_Encoding::get8BitEncoding()); } $message->setSubject($subject); $message->setTo($mailconf['recipient']); $message->setFrom(self::validEmailList($mailconf['fromEmail']), implode(' ', CoreGeneralUtility::trimExplode(',', $mailconf['fromName']))); $replyAddress = $mailconf['replyTo'] ?: $mailconf['fromEmail']; $replyName = implode(' ', CoreGeneralUtility::trimExplode(',', $mailconf['replyTo'] ? '' : $mailconf['fromName'])); $message->setReplyTo($replyAddress, $replyName); if (isset($mailconf['recipient_copy']) && $mailconf['recipient_copy'] != '') { if ($mailconf['recipient_copy'] != '') { $message->setCc($mailconf['recipient_copy']); } } $message->setReturnPath($mailconf['fromEmail']); $message->setPriority((int) $mailconf['priority']); // add Html content if ($mailconf['html']['useHtml'] && trim($mailconf['html']['content'])) { $message->addPart($mailconf['html']['content'], 'text/html'); } // add plain text content $message->addPart($mailconf['plain']['content']); // add attachment if (is_array($mailconf['attach'])) { foreach ($mailconf['attach'] as $file) { if ($file && file_exists($file)) { $message->attach(\Swift_Attachment::fromPath($file)); } } } foreach ($hooks as $hookObj) { if (method_exists($hookObj, 'postProcessMail')) { $message = $hookObj->postProcessMail($message, $mailconf, $additionalData); } } return $message->send(); } return false; }
function cmtx_email($to_email, $to_name, $subject, $body, $from_email, $from_name, $reply_email) { //sends an email global $cmtx_path; //globalise variables if (cmtx_setting('transport_method') == 'php-basic') { //set email headers $headers = 'From: ' . $from_name . ' <' . $from_email . '>' . "\r\n"; $headers .= 'Reply-To: ' . $reply_email . "\r\n"; $headers .= 'Content-Type: text/plain; charset=utf-8' . "\r\n"; //set recipient name if (!empty($to_name)) { $to_email = $to_name . " <{$to_email}>"; } //send email @mail($to_email, $subject, $body, $headers); } else { if (!class_exists('Swift')) { require_once $cmtx_path . 'includes/external/swift_mailer/lib/swift_required.php'; //load Swift Mailer } //set the transport method if (cmtx_setting('transport_method') == 'php') { $transport = Swift_MailTransport::newInstance(); } else { if (cmtx_setting('transport_method') == 'smtp') { $transport = Swift_SmtpTransport::newInstance(); $transport->setHost(cmtx_setting('smtp_host')); $transport->setPort(cmtx_setting('smtp_port')); if (cmtx_setting('smtp_encrypt') == 'ssl') { $transport->setEncryption('ssl'); } else { if (cmtx_setting('smtp_encrypt') == 'tls') { $transport->setEncryption('tls'); } } if (cmtx_setting('smtp_username') && cmtx_setting('smtp_password')) { $transport->setUsername(cmtx_setting('smtp_username')); $transport->setPassword(cmtx_setting('smtp_password')); } } else { if (cmtx_setting('transport_method') == 'sendmail') { $transport = Swift_SendmailTransport::newInstance(cmtx_setting('sendmail_path') . ' -bs'); } } } //create the Mailer using the created Transport $mailer = Swift_Mailer::newInstance($transport); //create the message $message = Swift_Message::newInstance(); //give the message a subject $message->setSubject($subject); //set the From address $message->setFrom(array($from_email => $from_name)); //set the Reply-To address $message->setReplyTo($reply_email); //set the To address if (empty($to_name)) { $message->setTo($to_email); } else { $message->setTo(array($to_email => $to_name)); } //give it a body $message->setBody($body); //set the format of message $message->setContentType('text/plain'); //set the charset as UTF-8 $message->setCharset('UTF-8'); //set the content-transfer-encoding to 8bit $message->setEncoder(Swift_Encoding::get8BitEncoding()); //set the maximum line length to 1000 $message->setMaxLineLength(1000); //send the message $result = $mailer->send($message); } }
/** * Invokes the HTML mailing class * Example for $mailconf * * $mailconf = array( * 'plain' => Array ( * 'content'=> '' // plain content as string * ), * 'html' => Array ( * 'content'=> '', // html content as string * 'path' => '', * 'useHtml' => '' // is set mail is send as multipart * ), * 'defaultCharset' => 'utf-8', // your chartset * 'encoding' => '8-bit', // your encoding * 'attach' => Array (), // your attachment as array * 'alternateSubject' => '', // is subject empty will be ste alternateSubject * 'recipient' => '', // comma seperate list of recipient * 'recipient_copy' => '', // bcc * 'fromEmail' => '', // fromMail * 'fromName' => '', // fromName * 'replyTo' => '', // replyTo * 'priority' => '3', // priority of your Mail * 1 = highest, * 5 = lowest, * 3 = normal * ); * * @param array $mailconf Configuration for the mailerengine * * @return bool */ public static function sendMail(array $mailconf) { $hookObjectsArr = array(); if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['commerce/lib/class.tx_commerce_div.php']['sendMail'])) { \TYPO3\CMS\Core\Utility\GeneralUtility::deprecationLog(' hook $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXTCONF\'][\'commerce/lib/class.tx_commerce_div.php\'][\'sendMail\'] is deprecated since commerce 1.0.0, it will be removed in commerce 1.4.0, please use instead $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXTCONF\'][\'commerce/Classes/Utility/GeneralUtility.php\'][\'sendMail\'] '); foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['commerce/lib/class.tx_commerce_div.php']['sendMail'] as $classRef) { $hookObjectsArr[] = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($classRef); } } if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['commerce/Classes/Utility/GeneralUtility.php']['sendMail'])) { foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['commerce/Classes/Utility/GeneralUtility.php']['sendMail'] as $classRef) { $hookObjectsArr[] = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($classRef); } } $additionalData = array(); if ($mailconf['additionalData']) { $additionalData = $mailconf['additionalData']; } foreach ($hookObjectsArr as $hookObj) { // this is the current hook if (method_exists($hookObj, 'preProcessMail')) { $hookObj->preProcessMail($mailconf, $additionalData); } } foreach ($hookObjectsArr as $hookObj) { if (method_exists($hookObj, 'ownMailRendering')) { return $hookObj->ownMailRendering($mailconf, $additionalData, $hookObjectsArr); } } // validate e-mail addesses $mailconf['recipient'] = self::validEmailList($mailconf['recipient']); if ($mailconf['recipient']) { $parts = preg_split('/<title>|<\\/title>/i', $mailconf['html']['content'], 3); if (trim($parts[1])) { $subject = strip_tags(trim($parts[1])); } elseif ($mailconf['plain']['subject']) { $subject = $mailconf['plain']['subject']; } else { $subject = $mailconf['alternateSubject']; } /** * Mail message * * @var \TYPO3\CMS\Core\Mail\MailMessage $message */ $message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage'); $message->setCharset($mailconf['defaultCharset']); if ($mailconf['encoding'] == 'base64') { $message->setEncoder(Swift_Encoding::getBase64Encoding()); } elseif ($mailconf['encoding'] == '8bit') { $message->setEncoder(Swift_Encoding::get8BitEncoding()); } $message->setSubject($subject); $message->setTo($mailconf['recipient']); $message->setFrom(self::validEmailList($mailconf['fromEmail']), implode(' ', \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $mailconf['fromName']))); $replyAddress = $mailconf['replyTo'] ?: $mailconf['fromEmail']; $replyName = implode(' ', \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $mailconf['replyTo'] ? '' : $mailconf['fromName'])); $message->setReplyTo($replyAddress, $replyName); if (isset($mailconf['recipient_copy']) && $mailconf['recipient_copy'] != '') { if ($mailconf['recipient_copy'] != '') { $message->setCc($mailconf['recipient_copy']); } } $message->setReturnPath($mailconf['fromEmail']); $message->setPriority((int) $mailconf['priority']); // add Html content if ($mailconf['html']['useHtml'] && trim($mailconf['html']['content'])) { $message->addPart($mailconf['html']['content'], 'text/html'); } // add plain text content $message->addPart($mailconf['plain']['content']); // add attachment if (is_array($mailconf['attach'])) { foreach ($mailconf['attach'] as $file) { if ($file && file_exists($file)) { $message->attach(Swift_Attachment::fromPath($file)); } } } foreach ($hookObjectsArr as $hookObj) { if (method_exists($hookObj, 'postProcessMail')) { $message = $hookObj->postProcessMail($message, $mailconf, $additionalData); } } return $message->send(); } return FALSE; }
private function _sendMail($from, $to, $subject, $messagePlain, $messageHtml = null, $cc = null, $bcc = null, $attachments = null) { if (!SWIFTAVAILABLE) { throw $this->throwException(GenericException::SWIFT_NOT_FOUND); } require_once 'Swift/lib/swift_required.php'; $subject = filter_var($subject, FILTER_SANITIZE_STRING); $messagePlain = filter_var($messagePlain, FILTER_SANITIZE_STRING); if (is_string($from)) { if (filter_var($from, FILTER_VALIDATE_EMAIL)) { $from = array($from => $from); } else { throw $this->throwException(ParameterException::EMAIL_EXCEPTION); } } else { if (is_array($from)) { // Only one sender $from = array_splice($from, 0, 1); foreach ($from as $key => $val) { if (filter_var($key, FILTER_VALIDATE_EMAIL)) { $from = array($key => filter_var($val, FILTER_SANITIZE_STRING)); } else { throw $this->throwException(ParameterException::EMAIL_EXCEPTION); } } } else { throw $this->throwException(ParameterException::EMAIL_EXCEPTION); } } // Validate e-mail addresses $receivers = (object) array('to' => $to, 'cc' => $cc, 'bcc' => $bcc); foreach ($receivers as &$receiver) { if ($receiver) { if (is_string($receiver)) { if (filter_var($receiver, FILTER_VALIDATE_EMAIL)) { $receiver = array($receiver => $receiver); } else { throw $this->throwException(ParameterException::EMAIL_EXCEPTION); } } else { if (is_array($receiver)) { foreach ($receiver as $key => $val) { if (is_array($val)) { foreach ($val as $vkey => $vval) { if (filter_var($vkey, FILTER_VALIDATE_EMAIL)) { $receiver[$vkey] = filter_var($vval, FILTER_SANITIZE_STRING); unset($receiver[$key]); } else { throw $this->throwException(ParameterException::EMAIL_EXCEPTION); } } } else { if (filter_var($key, FILTER_VALIDATE_EMAIL)) { // May be double, but you never know $receiver[$key] = filter_var($val, FILTER_SANITIZE_STRING); } else { if (filter_var($val, FILTER_VALIDATE_EMAIL)) { $receiver[$val] = filter_var($val, FILTER_SANITIZE_STRING); } else { throw $this->throwException(ParameterException::EMAIL_EXCEPTION); } } } } } else { throw $this->throwException(ParameterException::EMAIL_EXCEPTION); } } } } if (count($receivers->to) == 0 && count($receivers->cc) == 0 && count($receivers->bcc) == 0) { throw $this->throwException(ParameterException::EMAIL_EXCEPTION); } $transport = null; if (defined('TRANSPORT') && TRANSPORT == 'smtp') { $transport = \Swift_SmtpTransport::newInstance(SMTP, SMTPPORT); } else { if (defined('TRANSPORT') && TRANSPORT == 'sendmail') { $transport = \Swift_SendmailTransport::newInstance(); } else { $transport = \Swift_MailTransport::newInstance(); } } $mailer = \Swift_Mailer::newInstance($transport); $msg = \Swift_Message::newInstance(); //Give the message a subject $msg->setSubject($subject)->setMaxLineLength(1000)->setFrom($from); if (count($receivers->to) > 0) { $msg->setTo($receivers->to); } else { $msg->setTo($from); } if ($messageHtml != null) { $msg->setEncoder(\Swift_Encoding::get8BitEncoding()); $msg->setBody($messageHtml, 'text/html'); } if ($messagePlain != null && $messagePlain != false) { $msg->addPart($messagePlain, 'text/plain'); } if ($messageHtml != null) { $headers = $msg->getHeaders(); if ($headers) { $cte = $headers->get('Content-Transfer-Encoding'); if ($cte) { $cte->setValue('7bit'); } } } if ($attachments != null) { if (!is_array($attachments)) { $attachments = array($attachments); } foreach ($attachments as $att) { if (file_exists($att)) { $msg->attach(\Swift_Attachment::fromPath($att)); } else { if ($att instanceof \Swift_Attachment) { $msg->attach($att); } else { Connection::getInstance()->addTolog($att . ' does not exist and is therefore not attached to message with subject ' . $subject); } } } } if (count($receivers->cc) > 0) { $msg->setCc($receivers->cc); } if (count($receivers->bcc) > 0) { $msg->setBcc($receivers->bcc); } if (DISABLEMAIL) { return count($receivers->cc) + count($receivers->bcc) + count($receivers->to); } $result = $mailer->send($msg); return $result; }
/** * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully) * Sender name and email can be specified, if not specified * name and email of the platform admin are used * * @author Bert Vanderkimpen ICT&O UGent * @author Yannick Warnier <*****@*****.**> * * @param string name of recipient * @param string email of recipient * @param string email subject * @param string email body * @param string sender name * @param string sender e-mail * @param array extra headers in form $headers = array($name => $value) to allow parsing * @param array data file (path and filename) * @param array data to attach a file (optional) * @param bool True for attaching a embedded file inside content html (optional) * @return returns true if mail was sent * @see class.phpmailer.php */ function api_mail_html($recipient_name, $recipient_email, $subject, $body, $sender_name = '', $sender_email = '', $extra_headers = null, $data_file = array(), $embedded_image = false, $text_body = null) { $reply_to_mail = $sender_email; $reply_to_name = $sender_name; if (isset($extra_headers['reply_to'])) { $reply_to_mail = $extra_headers['reply_to']['mail']; $reply_to_name = $extra_headers['reply_to']['name']; } // Forcing the conversion. if (strpos($body, '<html>') === false) { $htmlBody = str_replace(array("\n\r", "\n", "\r"), '<br />', $body); $htmlBody = '<html><head></head><body>' . $htmlBody . '</body></html>'; } else { $htmlBody = $body; } if (!empty($text_body)) { $textBody = $text_body; } else { $textBody = $body; } try { $message = \Swift_Message::newInstance()->setSubject($subject)->setFrom(array($sender_email => $sender_name))->setTo(array($recipient_email => $recipient_name))->setReplyTo(array($reply_to_mail => $reply_to_name))->setBody(Container::getTemplate()->render('ChamiloCoreBundle:Mailer:Default/default.html.twig', array('content' => $htmlBody)), 'text/html')->addPart(Container::getTemplate()->render('ChamiloCoreBundle:Mailer:Default/default.text.twig', array('content' => $textBody)), 'text/plain')->setEncoder(Swift_Encoding::get8BitEncoding()); if (!empty($data_file)) { // Attach it to the message $message->attach(Swift_Attachment::fromPath($data_file['path']))->setFilename($data_file['filename']); } $type = $message->getHeaders()->get('Content-Type'); $type->setValue('text/html'); $type->setParameter('charset', 'utf-8'); Container::getMailer()->send($message); return true; } catch (Exception $e) { error_log($e->getMessage()); } return false; }
private function getEncoder(Email\Part $part) { $encoding = $part->getEncoding(); if (null === $encoding) { return null; } switch ($encoding) { case Email::ENCODING_BASE64: return \Swift_Encoding::getBase64Encoding(); case Email::ENCODING_QUOTED_PRINTABLE: return \Swift_Encoding::getQpEncoding(); case Email::ENCODING_8BIT: return \Swift_Encoding::get8BitEncoding(); case Email::ENCODING_7BIT: return \Swift_Encoding::get7BitEncoding(); case Email::ENCODING_RAW: return new \Swift_Mime_ContentEncoder_RawContentEncoder(); default: throw new \InvalidArgumentException('Unknown encoding "' . $encoding . '"'); } }
/** * Sends an HTML email using the phpmailer class (and multipart/alternative to downgrade gracefully) * Sender name and email can be specified, if not specified * name and email of the platform admin are used * * @author Bert Vanderkimpen ICT&O UGent * @author Yannick Warnier <*****@*****.**> * * @param string name of recipient * @param string email of recipient * @param string email subject * @param string email body * @param string sender name * @param string sender e-mail * @param array extra headers in form $headers = array($name => $value) to allow parsing * @param array data file (path and filename) * @param array data to attach a file (optional) * @param bool True for attaching a embedded file inside content html (optional) * @return returns true if mail was sent * @see class.phpmailer.php */ function api_mail_html($recipient_name, $recipient_email, $subject, $body, $sender_name = '', $sender_email = '', $extra_headers = null, $data_file = array(), $embedded_image = false, $text_body = null) { global $app; $reply_to_mail = $sender_email; $reply_to_name = $sender_name; if (isset($extra_headers['reply_to'])) { $reply_to_mail = $extra_headers['reply_to']['mail']; $reply_to_name = $extra_headers['reply_to']['name']; } // Forcing the conversion. if (strpos($body, '<html>') === false) { $htmlBody = str_replace(array("\n\r", "\n", "\r"), '<br />', $body); $htmlBody = '<html><head></head><body>' . $htmlBody . '</body></html>'; } else { $htmlBody = $body; } if (!empty($text_body)) { $textBody = $text_body; } else { $textBody = $body; } try { $message = \Swift_Message::newInstance()->setSubject($subject)->setFrom(array($sender_email => $sender_name))->setTo(array($recipient_email => $recipient_name))->setReplyTo(array($reply_to_mail => $reply_to_name))->setBody($htmlBody, 'text/html')->addPart($textBody, 'text/plain')->setEncoder(Swift_Encoding::get8BitEncoding()); if (!empty($data_file)) { // Attach it to the message $message->attach(Swift_Attachment::fromPath($data_file['path']))->setFilename($data_file['filename']); } $type = $message->getHeaders()->get('Content-Type'); $type->setValue('text/html'); $type->setParameter('charset', 'utf-8'); $app['monolog']->addDebug($message); $result = $app['mailer']->send($message); return $result; } catch (Exception $e) { //$app['monolog']->addDebug('Email address not valid:' . $e->getMessage()); } return false; /* $mail = new PHPMailer(); $mail->Mailer = $platform_email['SMTP_MAILER']; $mail->Host = $platform_email['SMTP_HOST']; $mail->Port = $platform_email['SMTP_PORT']; $mail->CharSet = $platform_email['SMTP_CHARSET']; $mail->WordWrap = 200; // Stay far below SMTP protocol 980 chars limit. if ($platform_email['SMTP_AUTH']) { $mail->SMTPAuth = 1; $mail->Username = $platform_email['SMTP_USER']; $mail->Password = $platform_email['SMTP_PASS']; } $mail->Priority = 3; // 5 = low, 1 = high $mail->AddCustomHeader('Errors-To: '.$platform_email['SMTP_FROM_EMAIL']); $mail->SMTPKeepAlive = true; if (($sender_email != '') && ($sender_name != '')) { $mail->AddReplyTo($sender_email, $sender_name); } if (isset($extra_headers['reply_to'])) { $mail->AddReplyTo($extra_headers['reply_to']['mail'], $extra_headers['reply_to']['name']); } // Attachments // $mail->AddAttachment($path); // $mail->AddAttachment($path, $filename); if ($sender_email != '') { $mail->From = $sender_email; $mail->Sender = $sender_email; //$mail->ConfirmReadingTo = $sender_email; // Disposition-Notification } else { $mail->From = $platform_email['SMTP_FROM_EMAIL']; $mail->Sender = $platform_email['SMTP_FROM_EMAIL']; //$mail->ConfirmReadingTo = $platform_email['SMTP_FROM_EMAIL']; // Disposition-Notification } if ($sender_name != '') { $mail->FromName = $sender_name; } else { $mail->FromName = $platform_email['SMTP_FROM_NAME']; } $mail->Subject = $subject; $mail->AltBody = strip_tags(str_replace('<br />',"\n", api_html_entity_decode($message))); // Send embedded image. if ($embedded_image) { // Get all images html inside content. preg_match_all("/<img\s+.*?src=[\"\']?([^\"\' >]*)[\"\']?[^>]*>/i", $message, $m); // Prepare new tag images. $new_images_html = array(); $i = 1; if (!empty($m[1])) { foreach ($m[1] as $image_path) { $real_path = realpath($image_path); $filename = basename($image_path); $image_cid = $filename.'_'.$i; $encoding = 'base64'; $image_type = mime_content_type($real_path); $mail->AddEmbeddedImage($real_path, $image_cid, $filename, $encoding, $image_type); $new_images_html[] = '<img src="cid:'.$image_cid.'" />'; $i++; } } // Replace origin image for new embedded image html. $x = 0; if (!empty($m[0])) { foreach ($m[0] as $orig_img) { $message = str_replace($orig_img, $new_images_html[$x], $message); $x++; } } } $message = str_replace(array("\n\r", "\n", "\r"), '<br />', $message); $mail->Body = '<html><head></head><body>'.$message.'</body></html>'; // Attachment ... if (!empty($data_file)) { $mail->AddAttachment($data_file['path'], $data_file['filename']); } // Only valid addresses are accepted. if (is_array($recipient_email)) { foreach ($recipient_email as $dest) { if (api_valid_email($dest)) { $mail->AddAddress($dest, $recipient_name); //$mail->AddAddress($dest, ($i > 1 ? '' : $recipient_name)); } } } else { if (api_valid_email($recipient_email)) { $mail->AddAddress($recipient_email, $recipient_name); } else { return 0; } } if (is_array($extra_headers) && count($extra_headers) > 0) { foreach ($extra_headers as $key => $value) { switch (strtolower($key)) { case 'reply-to': //the value here is the result of api_get_user_info() $sender_email = $value['email']; $sender_name = $value['complete_name']; $mail->AddReplyTo($sender_email, $sender_name); break; case 'encoding': case 'content-transfer-encoding': $mail->Encoding = $value; break; case 'charset': $mail->Charset = $value; break; case 'contenttype': case 'content-type': $mail->ContentType = $value; break; default: $mail->AddCustomHeader($key.':'.$value); break; } } } else { if (!empty($extra_headers)) { $mail->AddCustomHeader($extra_headers); } } // WordWrap the html body (phpMailer only fixes AltBody) FS#2988 $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap); // Send the mail message. if (!$mail->Send()) { //echo 'ERROR: mail not sent to '.$recipient_name.' ('.$recipient_email.') because of '.$mail->ErrorInfo.'<br />'; error_log('ERROR: mail not sent to '.$recipient_name.' ('.$recipient_email.') because of '.$mail->ErrorInfo.'<br />'); return 0; } // Clear all the addresses. $mail->ClearAddresses(); return 1; */ }
/** * Builds and sending an email, renders the email body with an twig template * * @param mixed $formDataObj * @param array $handlerConfigArr * @param mixed $handlerParameters * * @return bool false */ public function sendEmailHandler($formDataObj, $handlerConfigArr, $handlerParameters, $form) { $content = false; if (isset($handlerParameters['content'])) { $content = $handlerParameters['content']; } $location = false; if (isset($handlerParameters['location'])) { $location = $handlerParameters['location']; } $formDataArr = $this->getFormDataArray($formDataObj); $template = false; if (isset($handlerConfigArr['template'])) { $template = $this->formBuilderService->getTemplateOverride($handlerConfigArr['template']); } $subject = false; if (isset($handlerConfigArr['email_subject'])) { if (substr($handlerConfigArr['email_subject'], 0, 1) === '@') { $subject_mapping = substr($handlerConfigArr['email_subject'], 1); if (isset($formDataArr[$subject_mapping]['value'])) { $subject = $formDataArr[$subject_mapping]['value']; } } else { $subject = $handlerConfigArr['email_subject']; } // ToDo: subject mapping / static (intl) } $from = false; if (isset($handlerConfigArr['email_sender'])) { if (substr($handlerConfigArr['email_sender'], 0, 1) === '@') { $email_sender_mapping = substr($handlerConfigArr['email_sender'], 1); if (isset($formDataArr[$email_sender_mapping]['value'])) { // Check email addresses validity by using PHP's internal filter_var function if (filter_var($formDataArr[$email_sender_mapping]['value'], FILTER_VALIDATE_EMAIL)) { $from = $formDataArr[$email_sender_mapping]['value']; } } } else { // Check email addresses validity by using PHP's internal filter_var function if (filter_var($handlerConfigArr['email_sender'], FILTER_VALIDATE_EMAIL)) { $from = $handlerConfigArr['email_sender']; } } } $to = false; if (isset($handlerConfigArr['email_receiver'])) { if (substr($handlerConfigArr['email_receiver'], 0, 1) === '@') { $email_receiver_mapping = substr($handlerConfigArr['email_receiver'], 1); if (isset($formDataArr[$email_receiver_mapping]['value'])) { // Check email addresses validity by using PHP's internal filter_var function if (filter_var($formDataArr[$email_receiver_mapping]['value'], FILTER_VALIDATE_EMAIL)) { $to = $formDataArr[$email_receiver_mapping]['value']; } } } else { // Check email addresses validity by using PHP's internal filter_var function if (filter_var($handlerConfigArr['email_receiver'], FILTER_VALIDATE_EMAIL)) { $to = $handlerConfigArr['email_receiver']; } } } $logging = false; if (isset($handlerConfigArr['logging']) && $handlerConfigArr['logging'] === true) { $logging = true; } $debug = false; if (isset($handlerConfigArr['debug']) && $handlerConfigArr['debug'] === true) { $debug = true; } $bcc = array(); if (isset($handlerConfigArr['email_bcc'])) { $bcc = $handlerConfigArr['email_bcc']; } if ($template !== false && $subject !== false && $from !== false && $to !== false) { // ToDo: render template inline if $template false $templateContent = $this->container->get('twig')->loadTemplate($template); $templateParameters = array('form' => $form->createView(), 'form_data_array' => $formDataArr, 'form_data_object' => $formDataObj, 'content' => $content, 'location' => $location); $bodyTextHtml = $templateContent->renderBlock('body_text_html', $templateParameters); $bodyTextPlain = $templateContent->renderBlock('body_text_plain', $templateParameters); $message = \Swift_Message::newInstance()->setEncoder(\Swift_Encoding::get8BitEncoding())->setSubject($subject)->setFrom($from)->setTo($to)->setBcc($bcc)->setBody($bodyTextHtml, 'text/html')->addPart($bodyTextPlain, 'text/plain'); if ($debug === false) { $this->mailer->send($message); } if ($logging === true) { $msgId = substr($message->getHeaders()->get('Message-ID')->getFieldBody(), 1, -1); //$dump = $message->toString(); <- this is the "real" output sent by the mailer $dump = $msgId . "\n\n" . $bodyTextPlain . $bodyTextHtml; // <- this is the "clean" uncoded output fetched directly from the template // $dump = str_replace( 'search', '', $message->toString() ); $log_dir = $this->container->getParameter('kernel.logs_dir') . '/formbuilder/'; if (is_dir($log_dir) === false) { mkdir($log_dir); } file_put_contents($log_dir . time() . '_' . $msgId, $dump); } } else { if ($debug == true) { $error = 'Error: All parameters ($template, $subject, $from, $to) must be provided <br> <br> This error was thrown on line: <font color="#5f9ea0">' . __LINE__ . '</font><br>' . 'Of file: <font color="#5f9ea0">' . __FILE__ . '</font><br>' . 'Inside of function: <font color="#5f9ea0">' . __FUNCTION__ . '</font> <br>' . '<br> <font color="red">Warning: </font> if this error is shown in production, disable debug!'; die($error); } else { die("search for: error code #244"); } } return false; }
/** * Specifies the encoding scheme in the message. * * @param string $encoding * * @return $this * @throws SwiftMailerException */ public function setContentTransferEncoding($encoding) { switch ($encoding) { case '7bit': $encoder = \Swift_Encoding::get7BitEncoding(); break; case '8bit': $encoder = \Swift_Encoding::get8BitEncoding(); break; case 'base64': $encoder = \Swift_Encoding::getBase64Encoding(); break; case 'qp': $encoder = \Swift_Encoding::getQpEncoding(); break; default: throw new SwiftMailerException('Invalid encoding name provided. Valid encodings are [7bit, 8bit, base64, qp].'); break; } $this->message->setEncoder($encoder); return $this; }
/** * Send of the email using php mail function. * * @var array $recipient: the recipient array. array($name => $mail) * @return boolean true if there is recipient and content, otherwise false */ function sendTheMail($recipient) { // $conf = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['direct_mail']; // init the swiftmailer object /** @var $mailer \TYPO3\CMS\Core\Mail\MailMessage */ $mailer = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage'); $mailer->setFrom(array($this->from_email => $this->from_name)); $mailer->setSubject($this->subject); $mailer->setPriority($this->priority); if ($this->replyto_email) { $mailer->setReplyTo(array($this->replyto_email => $this->replyto_name)); } else { $mailer->setReplyTo(array($this->from_email => $this->from_name)); } //setting additional header // organization and TYPO3MID $header = $mailer->getHeaders(); $header->addTextHeader('X-TYPO3MID', $this->TYPO3MID); if ($this->organisation) { $header->addTextHeader('Organization', $this->organisation); } if (GeneralUtility::validEmail($this->dmailer['sys_dmail_rec']['return_path'])) { $mailer->setReturnPath($this->dmailer['sys_dmail_rec']['return_path']); } //set the recipient $mailer->setTo($recipient); // TODO: setContent should set the images (includeMedia) or add attachment $this->setContent($mailer); if ($this->encoding == 'base64') { $mailer->setEncoder(\Swift_Encoding::getBase64Encoding()); } if ($this->encoding == '8bit') { $mailer->setEncoder(\Swift_Encoding::get8BitEncoding()); } //TODO: do we really need the return value? $sent = $mailer->send(); $failed = $mailer->getFailedRecipients(); //unset the mailer object unset($mailer); // Delete temporary files // see setContent, where temp images are downloaded if (!empty($this->tempFileList)) { foreach ($this->tempFileList as $tempFile) { if (file_exists($tempFile)) { unlink($tempFile); } } } }
/** * Send of the email using php mail function. * * @param string/array $recipient The recipient array. array($name => $mail) * @param array $recipRow Recipient's data array * * @return void */ function sendTheMail($recipient, $recipRow = null) { // init the swiftmailer object /* @var $mailer \TYPO3\CMS\Core\Mail\MailMessage */ $mailer = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage'); $mailer->setFrom(array($this->from_email => $this->from_name)); $mailer->setSubject($this->subject); $mailer->setPriority($this->priority); if ($this->replyto_email) { $mailer->setReplyTo(array($this->replyto_email => $this->replyto_name)); } else { $mailer->setReplyTo(array($this->from_email => $this->from_name)); } // setting additional header // organization and TYPO3MID $header = $mailer->getHeaders(); $header->addTextHeader('X-TYPO3MID', $this->TYPO3MID); if ($this->organisation) { $header->addTextHeader('Organization', $this->organisation); } // Hook to edit or add the mail headers if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/direct_mail']['res/scripts/class.dmailer.php']['mailHeadersHook'])) { $mailHeadersHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/direct_mail']['res/scripts/class.dmailer.php']['mailHeadersHook']; if (is_array($mailHeadersHook)) { $hookParameters = array('row' => &$recipRow, 'header' => &$header); $hookReference =& $this; foreach ($mailHeadersHook as $hookFunction) { GeneralUtility::callUserFunction($hookFunction, $hookParameters, $hookReference); } } } if (GeneralUtility::validEmail($this->dmailer['sys_dmail_rec']['return_path'])) { $mailer->setReturnPath($this->dmailer['sys_dmail_rec']['return_path']); } // set the recipient $mailer->setTo($recipient); // TODO: setContent should set the images (includeMedia) or add attachment $this->setContent($mailer); if ($this->encoding == 'base64') { $mailer->setEncoder(\Swift_Encoding::getBase64Encoding()); } if ($this->encoding == '8bit') { $mailer->setEncoder(\Swift_Encoding::get8BitEncoding()); } // TODO: do we really need the return value? $sent = $mailer->send(); $failed = $mailer->getFailedRecipients(); // unset the mailer object unset($mailer); // Delete temporary files // see setContent, where temp images are downloaded if (!empty($this->tempFileList)) { foreach ($this->tempFileList as $tempFile) { if (file_exists($tempFile)) { unlink($tempFile); } } } }
/** * Creates a new user for the platform * @author Hugues Peeters <*****@*****.**>, * @author Roan Embrechts <*****@*****.**> * @param string Firstname * @param string Lastname * @param int Status (1 for course tutor, 5 for student, 6 for anonymous) * @param string e-mail address * @param string Login * @param string Password * @param string Any official code (optional) * @param string User language (optional) * @param string Phone number (optional) * @param string Picture URI (optional) * @param string Authentication source (optional, defaults to 'platform', dependind on constant) * @param string Account expiration date (optional, defaults to '0000-00-00 00:00:00') * @param int Whether the account is enabled or disabled by default * @param int The department of HR in which the user is registered (optional, defaults to 0) * @param array Extra fields * @param string Encrypt method used if password is given encrypted. Set to an empty string by default * @return mixed new user id - if the new user creation succeeds, false otherwise * @desc The function tries to retrieve $_user['user_id'] from the global space. If it exists, $_user['user_id'] is the creator id. If a problem arises, it stores the error message in global $api_failureList * @assert ('Sam','Gamegie',5,'*****@*****.**','jo','jo') > 1 * @assert ('Pippin','Took',null,null,'jo','jo') === false */ public static function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $language = '', $phone = '', $picture_uri = '', $auth_source = PLATFORM_AUTH_SOURCE, $expiration_date = '0000-00-00 00:00:00', $active = 1, $hr_dept_id = 0, $extra = null, $encrypt_method = '', $send_mail = false) { global $_configuration; $original_password = $password; $access_url_id = 1; if (api_get_multiple_access_url()) { $access_url_id = api_get_current_access_url_id(); } if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_users']) && $_configuration[$access_url_id]['hosting_limit_users'] > 0) { $num = self::get_number_of_users(); if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) { return api_set_failure('portal users limit reached'); } } if ($status === 1 && is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_teachers']) && $_configuration[$access_url_id]['hosting_limit_teachers'] > 0) { $num = self::get_number_of_users(1); if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) { return api_set_failure('portal teachers limit reached'); } } $firstName = Security::remove_XSS($firstName); $lastName = Security::remove_XSS($lastName); $loginName = Security::remove_XSS($loginName); $phone = Security::remove_XSS($phone); // database table definition $table_user = Database::get_main_table(TABLE_MAIN_USER); //Checking the user language $languages = api_get_languages(); if (!in_array($language, $languages)) { $language = Container::getTranslator()->getLocale(); } $creator_id = api_get_user_id(); // First check wether the login already exists if (!self::is_username_available($loginName)) { return api_set_failure('login-pass already taken'); } if (empty($encrypt_method)) { $password = api_get_encrypted_password($password); } else { if ($_configuration['password_encryption'] === $encrypt_method) { if ($encrypt_method == 'md5' && !preg_match('/^[A-Fa-f0-9]{32}$/', $password)) { return api_set_failure('encrypt_method invalid'); } else { if ($encrypt_method == 'sha1' && !preg_match('/^[A-Fa-f0-9]{40}$/', $password)) { return api_set_failure('encrypt_method invalid'); } } } else { return api_set_failure('encrypt_method invalid'); } } //@todo replace this date with the api_get_utc_date function big problem with users that are already registered $current_date = api_get_utc_datetime(); $em = Database::getManager(); $expirationDate = new \DateTime($expiration_date); $user = new \Chamilo\UserBundle\Entity\User(); $user->setLastname($lastName)->setFirstname($firstName)->setUsername($loginName)->setPassword($password)->setEmail($email)->setOfficialCode($official_code)->setPictureUri($picture_uri)->setCreatorId($creator_id)->setAuthSource($auth_source)->setPhone($phone)->setLanguage($language)->setExpirationDate($expirationDate)->setHrDeptId($hr_dept_id)->setActive($active); /*$sql = "INSERT INTO $table_user ". "SET lastname = '".Database::escape_string(trim($lastName))."',". "firstname = '".Database::escape_string(trim($firstName))."',". "username = '******',". "status = '".Database::escape_string($status)."',". "password = '******',". "email = '".Database::escape_string($email)."',". "official_code = '".Database::escape_string($official_code)."',". "picture_uri = '".Database::escape_string($picture_uri)."',". "creator_id = '".Database::escape_string($creator_id)."',". "auth_source = '".Database::escape_string($auth_source)."',". "phone = '".Database::escape_string($phone)."',". "language = '".Database::escape_string($language)."',". "registration_date = '".$current_date."',". "expiration_date = '".Database::escape_string($expiration_date)."',". "hr_dept_id = '".Database::escape_string($hr_dept_id)."',". "active = '".Database::escape_string($active)."'"; $result = Database::query($sql);*/ $em->persist($user); $em->flush(); if ($user) { $userId = $user->getId(); if (api_get_multiple_access_url()) { UrlManager::add_user_to_url($userId, api_get_current_access_url_id()); } else { //we are adding by default the access_url_user table with access_url_id = 1 UrlManager::add_user_to_url($userId, 1); } $group = $em->getRepository('ChamiloUserBundle:Group')->find($status); $user->addGroup($group); //$user->addRole($roleName); $em->persist($user); $em->flush(); if (!empty($email) && $send_mail) { $recipient_name = api_get_person_name($firstName, $lastName, null, PERSON_NAME_EMAIL_ADDRESS); $emailsubject = '[' . api_get_setting('platform.site_name') . '] ' . get_lang('YourReg') . ' ' . api_get_setting('platform.site_name'); $sender_name = api_get_person_name(api_get_setting('platform.administrator_name'), api_get_setting('platform.administrator_surname'), null, PERSON_NAME_EMAIL_ADDRESS); $email_admin = api_get_setting('platform.administrator_email'); $params = array('complete_user_name' => api_get_person_name($firstName, $lastName), 'login_name' => $loginName, 'password' => stripslashes($original_password)); $message = \Swift_Message::newInstance()->setSubject($emailsubject)->setFrom(array($email_admin => $sender_name))->setTo(array($email => $recipient_name))->setBody(Container::getTemplate()->render('ChamiloCoreBundle:Mailer:User/new_user.html.twig', $params), 'text/html')->addPart(Container::getTemplate()->render('ChamiloCoreBundle:Mailer:User/new_user.text.twig', $params), 'text/plain')->setEncoder(Swift_Encoding::get8BitEncoding()); $type = $message->getHeaders()->get('Content-Type'); $type->setValue('text/html'); $type->setParameter('charset', 'utf-8'); Container::getMailer()->send($message); /* MANAGE EVENT WITH MAIL */ /*if (EventsMail::check_if_using_class('user_registration')) { $values["about_user"] = $return; $values["password"] = $original_password; $values["send_to"] = array($return); $values["prior_lang"] = null; EventsDispatcher::events('user_registration', $values); } else { @api_mail_html($recipient_name, $email, $emailsubject, $emailbody, $sender_name, $email_admin); }*/ /* ENDS MANAGE EVENT WITH MAIL */ } // Add event to system log $user_id_manager = api_get_user_id(); $user_info = api_get_user_info($userId); Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $userId, api_get_utc_datetime(), $user_id_manager); Event::addEvent(LOG_USER_CREATE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), $user_id_manager); } else { return api_set_failure('error inserting in Database'); } if (is_array($extra) && count($extra) > 0) { $res = true; foreach ($extra as $fname => $fvalue) { $res = $res && self::update_extra_field_value($userId, $fname, $fvalue); } } self::update_extra_field_value($userId, 'already_logged_in', 'false'); return $userId; }