/** * @param \Swift_Mime_MimeEntity $message * * @throws \TijsVerkoyen\CssToInlineStyles\Exception */ private function convert(\Swift_Mime_MimeEntity $message) { if ($message->getContentType() !== 'text/plain') { $this->inliner->setCSS(''); $this->inliner->setHTML($message->getBody()); $message->setBody($this->inliner->convert()); } }
/** * @param $html * * @return string */ public function transformCssToInlineStyles($html) { $this->inliner->setHTML($html); foreach ($this->getStylesheets($html) as $css) { $this->inliner->setCSS($css); } return $this->inliner->convert(); }
public function compile($body) { $css = file_get_contents(__DIR__ . '/../../../bower_components/github-markdown-css/github-markdown.css'); $html = '<div class="markdown-body">' . $this->markdowner->convertToHtml($body) . '</div>'; $this->inliner->setCSS($css); $this->inliner->setHTML($html); return $this->inliner->convert(); }
/** * @param Swift_Events_SendEvent $event */ public function beforeSendPerformed(Swift_Events_SendEvent $event) { $message = $event->getMessage(); $this->converter->setEncoding($message->getCharset()); if ($message->getContentType() === 'text/html') { $this->converter->setHTML($message->getBody()); $message->setBody($this->converter->convert()); } foreach ($message->getChildren() as $part) { if (strpos($part->getContentType(), 'text/html') === 0) { $this->converter->setHTML($part->getBody()); $part->setBody($this->converter->convert()); } } }
/** * A parser function or rebuilder to inline original file * into an email based html * * @param mixed $record assigned key from inliner config * @return null */ protected function parse($record) { # - instatiate the package inliner $inliner = new CssToInlineStyles(); # - let's get the views dir combine the record file $base_file = remove_double_slash(View::getViewsDir() . $record->file . '.*'); # - now get all related glob $related_files = glob($base_file); if (empty($related_files) == true) { $this->comment(' System can\'t find the file: ' . $base_file); return; } # - set the html $inliner->setHTML(file_get_contents($related_files[0])); # - set the css files $inliner->setCSS($this->combineCss($record['css'])); # - get the dirname and file name $dirname = dirname($related_files[0]); $converted_name = basename($record->file) . '-inligned.volt'; # - overwrite or create a file based on the dirname # and file name file_put_contents($dirname . '/' . $converted_name, rawurldecode($inliner->convert())); # - log, show some sucess $this->comment(' ' . basename($record->file) . ' inlined! saved as ' . $converted_name); }
/** * Inline CSS inside of HTML and return resulting HTML * @param string $html * @param string $css * @param bool $outputXHTML * @return string */ public function inlineCSS($html, $css, $outputXHTML = false) { $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'); $this->cssToInlineStyles->setHTML($html); $this->cssToInlineStyles->setCSS($css); return $this->cssToInlineStyles->convert($outputXHTML); }
public function send($view, array $data, $callback) { $message = new Message(new Swift_Message()); if ($callback instanceof Closure) { // callback must assign $to and $subject, deal with it call_user_func($callback, $message); } else { throw new InvalidArgumentException('Callback is not valid.'); } $m = $message->getSwiftMessage(); $filteredTo = array_filter(array_keys($message->getTo()), function ($email) { $skip = DB::table('ses_feedback')->where('email', $email)->first(); if ($skip) { Log::info("skipping email:{$email}"); } return !$skip; }); if ($filteredTo) { $converter = new CssToInlineStyles(); $converter->setEncoding($message->getCharset()); $converter->setStripOriginalStyleTags(); $converter->setUseInlineStylesBlock(); $converter->setExcludeMediaQueries(false); $converter->setCleanup(); $converter->setHTML(View::make($view, $data)->render()); $body = $converter->convert(); $config = Config::get('services.amazon'); SesClient::factory($config)->sendEmail(array('Source' => $config['from'], 'Destination' => array('ToAddresses' => $filteredTo), 'Message' => array('Subject' => array('Data' => $m->getSubject(), 'Charset' => 'UTF-8'), 'Body' => array('Text' => array('Data' => strip_tags(str_replace("<br/>", "\n", $body)), 'Charset' => 'UTF-8'), 'Html' => array('Data' => $body, 'Charset' => 'UTF-8'))), 'ReplyToAddresses' => array())); } }
function inline_newsletter($css, $content) { // create instance $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($content); $cssToInlineStyles->setCSS($css); // output return $cssToInlineStyles->convert(); }
/** * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(\Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); $converter = new CssToInlineStyles(); $converter->setEncoding($message->getCharset()); $converter->setUseInlineStylesBlock(); $converter->setCleanup(); if ($message->getContentType() === 'text/html' || $message->getContentType() === 'multipart/alternative' && $message->getBody() || $message->getContentType() === 'multipart/mixed' && $message->getBody()) { $converter->setHTML($message->getBody()); $message->setBody($converter->convert()); } foreach ($message->getChildren() as $part) { if (strpos($part->getContentType(), 'text/html') === 0) { $converter->setHTML($part->getBody()); $part->setBody($converter->convert()); } } }
/** * Convert to inlined CSS * * @return string * @throws \TijsVerkoyen\CssToInlineStyles\Exception */ public function convert() { $converter = new CssToInlineStyles(); $converter->setUseInlineStylesBlock(); $converter->setCleanup(); $converter->setStripOriginalStyleTags(); $converter->setHTML($this->view); $content = $converter->convert(); return $content; }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $client = $this->getHttpClient(); // Inline CSS here $converter = new CssToInlineStyles(); $converter->setEncoding($message->getCharset()); $converter->setUseInlineStylesBlock(); $converter->setCleanup(); if ($message->getContentType() === 'text/html' || $message->getContentType() === 'multipart/alternative' && $message->getBody()) { $converter->setHTML($message->getBody()); $message->setBody($converter->convert()); } foreach ($message->getChildren() as $part) { if (strpos($part->getContentType(), 'text/html') === 0) { $converter->setHTML($part->getBody()); $part->setBody($converter->convert()); } } // Call the API $client->post($this->url, ['auth' => ['api', $this->key], 'body' => ['to' => $this->getTo($message), 'message' => new PostFile('message', (string) $message)]]); }
public function getRenderedHtmlMessage() { if (empty($this->htmlMessage)) { $template = $this->getTemplateName($this->templateId, 'email.html'); if (!empty($this->cssFile)) { $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($this->twigEngine->render($template, $this->templateVars)); $cssToInlineStyles->setCSS(file_get_contents($this->cssFile)); $this->htmlMessage = $cssToInlineStyles->convert(); } else { $this->htmlMessage = $this->twigEngine->render($template, $this->templateVars); } } return $this->htmlMessage; }
/** * Turns a unformatted email into a email with specified inline CSS * * @param String $sRawHTML, string containing the raw HTML of the email * @param String $sCSS, string containing the CSS you wish to make inline * * @return String */ public function genInlineCode($sRawHTML, $sCSS) { /* * The class below seems to strip out and other escaped chars. This is a temp * fix and won't escape all chars. */ $sRawHTML = preg_replace("/&#?[a-z0-9]+;/i", '{{nbsp}}', $sRawHTML); $sInlineCode = $sRawHTML; $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($sRawHTML); $cssToInlineStyles->setCSS($sCSS); $sInlineCode = $cssToInlineStyles->convert(); // restore escaped $sInlineCode = str_replace('{{nbsp}}', ' ', $sInlineCode); $sInlineCode = str_replace('{{padding}}', $this->aSettings['padding'], $sInlineCode); return $sInlineCode; }
/** * applyCSS * * Describe here what the function should do * * @since 1-jul-2015 * @access private * @return applyCSS **/ private function applyCSS($html, $css) { $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($html); $cssToInlineStyles->setCSS($css); return $cssToInlineStyles->convert(); }
/** * Reset the internal inliner object. */ protected function cleanup() { $this->internalInliner->setHTML(''); $this->internalInliner->setCSS(''); }
/** * Converts all css to inline styles * * @param string $html * @return string */ private function cssToInlineStyles($html) { $charset = Model::getContainer()->getParameter('kernel.charset'); $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($html); $cssToInlineStyles->setUseInlineStylesBlock(true); $cssToInlineStyles->setEncoding($charset); return (string) $cssToInlineStyles->convert(); }
/** * Execute compile command */ protected function execute(InputInterface $input, OutputInterface $output) { //get project name & set source/output dirs $project = $input->getArgument('project'); $this->config = new \Implico\Email\Config($project, $input->getOption('dir')); if ($error = $this->config->getErrors()) { switch ($error) { case 'projectNotFound': $output->writeln('<fg=red>ERROR: project directory not found</fg=red>'); exit(1); break; } } SmartyUtils::init($this->config); //get script name(s) $scripts = $input->getOption('script'); //if script name(s) not passed, set all scripts (exclude dirs) if (!$scripts) { $scripts = array_filter(array_diff(scandir($this->config['scriptsDir']), array('.', '..')), function ($script) { return !is_dir($this->config['scriptsDir'] . $script); }); } //add ".tpl" extension when applicable foreach ($scripts as $i => $script) { if (strpos($script, '.') === false) { $scripts[$i] = $script . '.tpl'; } } //get watch option $watch = $input->getOption('watch'); //get output option $outputMode = $input->getOption('output'); //create & configure Smarty object $smarty = new \Smarty(); $smarty->setCompileDir(IE_SMARTY_COMPILE_DIR); $smarty->addPluginsDir(IE_SMARTY_PLUGINS_DIR); $smarty->addPluginsDir(IE_SMARTY_CUSTOM_PLUGINS_DIR); $smarty->compile_check = false; $smarty->force_compile = true; $smarty->error_reporting = E_ALL; $smarty->registerClass('SmartyUtils', 'Implico\\Email\\Utils\\Smarty'); //set directories $smarty->setTemplateDir(array(0 => $this->config['dir'], 'core' => IE_CORE_DIR, 'layouts' => $this->config['layoutsDir'], 'scripts' => $this->config['scriptsDir'], 'styles' => $this->config['stylesDir'])); //master config file $smarty->configLoad(IE_CORE_DIR . 'config.conf'); //optional master custom config file $customConf = IE_CUSTOM_DIR . 'config.conf'; if (file_exists($customConf)) { $smarty->configLoad($customConf); } //console message for watching if ($watch) { $output->writeln('Watching for changes...'); } //main loop - watch for changes (or execute once if not watching) $compileNo = 1; $compileDirStamp = ''; //dirs to inspect file change $checkDirs = array($this->config['configsDir'], $this->config['configsScriptsDir'], $this->config['layoutsDir'], $this->config['scriptsDir'], $this->config['stylesDir']); //set output mode variables $outputMinified = in_array('m', $outputMode); $outputFormatted = in_array('f', $outputMode); //formatter object $formatter = null; //css inliner object $cssToInlineStyles = new CssToInlineStyles(); while (true) { //compile only if not watching or the dirs filestamp changes if (!$watch || $compileDirStamp != $this->getDirStamp($checkDirs)) { //clear compiled templates $smarty->clearCompiledTemplate(); //Smarty assign project-specific config file path $configFile = $this->config['configsDir'] . 'config.conf'; $loadConfigFile = file_exists($configFile); //set random complile_id (forces Smarty to compile) $smarty->compile_id = uniqid(); //list of compiled scripts $compiledScripts = $scripts; //fetch & save templates foreach ($scripts as $i => $script) { //script name without extension $scriptName = substr($script, 0, strrpos($script, '.')); $smarty->clearConfig(); if ($loadConfigFile) { $smarty->configLoad($configFile); } //set script-specific config file path if exists $configFileScript = $this->config['configsScriptsDir'] . $scriptName . '.conf'; if (file_exists($configFileScript)) { $smarty->configLoad($configFileScript); } //lazy create indenter if ($outputFormatted && !$formatter) { $formatter = new \Gajus\Dindent\Indenter(array('indentation_character' => $smarty->getConfigVars('indentChar'))); } //set encoding $outputEncoding = $smarty->getConfigVars('encoding'); if (!$outputEncoding) { $outputEncoding = 'utf-8'; } $outputEncodingUtf8 = strtoupper($outputEncoding) == 'UTF-8'; try { //get the html $html = $smarty->fetch($this->config['scriptsDir'] . $script); //get inline styles $inlineCss = $smarty->fetch($this->config['stylesDir'] . 'inline.tpl'); if (trim($inlineCss)) { $cssToInlineStyles->setHTML($html); $cssToInlineStyles->setCSS($inlineCss); $html = $cssToInlineStyles->convert(); } //save minified if ($outputMinified) { $htmlSave = $html; if (!$outputEncodingUtf8) { $htmlSave = mb_convert_encoding($htmlSave, $outputEncoding, 'utf-8'); } //max line width = 900 chars $maxPerLine = 750; $endLine = false; $newHtml = ''; for ($i = 0; $i < mb_strlen($htmlSave, $outputEncoding); $i++) { if ($i % $maxPerLine == 0 && $i > 0) { $endLine = true; } $curChar = mb_substr($htmlSave, $i, 1, $outputEncoding); $newHtml .= $curChar; if ($endLine) { if ($curChar == '>') { $newHtml .= PHP_EOL; $endLine = false; } } } $htmlSave = $newHtml; $this->saveOutput($this->config['outputsDir'] . $scriptName . '.min.html', $htmlSave); } //save formatted if ($outputFormatted) { $htmlSave = $formatter->indent($html); if (!$outputEncodingUtf8) { $htmlSave = mb_convert_encoding($htmlSave, $outputEncoding, 'utf-8'); } $this->saveOutput($this->config['outputsDir'] . $scriptName . '.html', $htmlSave, true); } } catch (\Exception $e) { $output->writeln('<fg=red>' . $e->getMessage() . '</fg=red>'); $compiledScripts[$i] .= ' <fg=red>(ERROR)</fg=red>'; } } //console info message $output->writeln(($watch ? '#' . $compileNo++ . ' ' : '') . 'Compiled ' . date('d-m-Y H:i:s') . ' ' . implode(', ', $compiledScripts)); } //break if not watching if (!$watch) { break; } //calculate dirs filestamp to compare $compileDirStamp = $this->getDirStamp($checkDirs); //pause usleep(500000); } }
/** * @param $string * @param null $document * @return mixed * @throws \Exception */ public static function embedAndModifyCss($string, $document = null) { if ($document && $document instanceof Model\Document == false) { throw new \Exception('$document has to be an instance of Document'); } //matches all <link> Tags preg_match_all("@<link.*?href\\s*=\\s*[\"'](.*?)[\"'].*?(/?>|</\\s*link>)@is", $string, $matches); if (!empty($matches[0])) { $css = ""; foreach ($matches[0] as $key => $value) { $fullMatch = $matches[0][$key]; $path = $matches[1][$key]; $fileContent = ""; $fileInfo = []; if (stream_is_local($path)) { $fileInfo = self::getNormalizedFileInfo($path, $document); if (in_array($fileInfo['fileExtension'], ['css', 'less'])) { if (is_readable($fileInfo['filePathNormalized'])) { if ($fileInfo['fileExtension'] == 'css') { $fileContent = file_get_contents($fileInfo['filePathNormalized']); } else { $fileContent = \Pimcore\Tool\Less::compile($fileInfo['filePathNormalized']); $fileContent = str_replace('/**** compiled with lessphp ****/', '', $fileContent); } } } } elseif (strpos($path, "http") === 0) { $fileContent = \Pimcore\Tool::getHttpData($path); $fileInfo = ["fileUrlNormalized" => $path]; } if ($fileContent) { $fileContent = self::normalizeCssContent($fileContent, $fileInfo); $css .= "\n\n\n"; $css .= $fileContent; // remove <link> tag $string = str_replace($fullMatch, '', $string); } } $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($string); $cssToInlineStyles->setCSS($css); $string = $cssToInlineStyles->convert(); } return $string; }
private static function send() { $html = view(self::$view, self::$data)->render(); $css = file_get_contents(PUBLIC_FOLDER . "/css/emails.css"); $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($html); $cssToInlineStyles->setCSS($css); self::$content = $cssToInlineStyles->convert(); if (env('APP_DEBUG')) { foreach (self::$to as &$to) { $to = uniqid() . "_" . $to; } foreach (self::$cc as &$cc) { $cc = uniqid() . "_" . $cc; } foreach (self::$bcc as &$bcc) { $bcc = uniqid() . "_" . $bcc; } if (Auth::user() && Auth::user()->active_contact->person_id == Auth::user()->person_id) { self::add("to", Auth::user()->active_contact->email); } foreach (self::$bcc_debug_mode as $bcc) { self::add("bcc", $bcc); } } $data['subject'] = self::$subject; $data['content'] = self::$content; $data['to'] = self::$to; $data['cc'] = self::$cc; $data['bcc'] = self::$bcc; Mail::queue('emails/dummy', array('content' => $data['content']), function ($message) use($data) { $message->setBody($data['content'], 'text/html'); $message->to($data['to']); $message->cc($data['cc']); $message->bcc($data['bcc']); $message->subject($data['subject']); }); self::clear(); }
/** * @param $string * @param null $document * @return mixed * @throws \Exception */ public static function embedAndModifyCss($string, $document = null) { if ($document && $document instanceof Model\Document == false) { throw new \Exception('$document has to be an instance of Document'); } //matches all <link> Tags preg_match_all("@<link.*?href\\s*=\\s*[\"']([^http].*?)[\"'].*?(/?>|</\\s*link>)@is", $string, $matches); if (!empty($matches[0])) { $css = ""; foreach ($matches[0] as $key => $value) { $fullMatch = $matches[0][$key]; $path = $matches[1][$key]; $fileInfo = self::getNormalizedFileInfo($path, $document); if (in_array($fileInfo['fileExtension'], array('css', 'less'))) { if (is_readable($fileInfo['filePathNormalized'])) { if ($fileInfo['fileExtension'] == 'css') { $fileContent = file_get_contents($fileInfo['filePathNormalized']); } else { $fileContent = \Pimcore\Tool\Less::compile($fileInfo['filePathNormalized']); $fileContent = str_replace('/**** compiled with lessphp ****/', '', $fileContent); } if ($fileContent) { $fileContent = self::normalizeCssContent($fileContent, $fileInfo); $css .= "\n\n\n"; $css .= $fileContent; // remove <link> tag $string = str_replace($fullMatch, '', $string); } } } } $autoloader = \Zend_Loader_Autoloader::getInstance(); $autoloader->registerNamespace('TijsVerkoyen'); $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($string); $cssToInlineStyles->setCSS($css); $string = $cssToInlineStyles->convert(); } return $string; }
<?php //require require_once 'CssToInlineStyles.php'; //require_once 'config.php'; use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles; // create instance $cssToInlineStyles = new CssToInlineStyles(); $html = file_get_contents('./examples/sumo/index.htm'); $css = file_get_contents('./examples/sumo/style.css'); $cssToInlineStyles->setHTML($html); $cssToInlineStyles->setCSS($css); // output echo $cssToInlineStyles->convert();
protected function _addInlineCSS(CssToInlineStyles $CssInline = null) { if (empty($this->style)) { throw new Exception("missing_stylesheet"); } $CssInline->setHTML($this->_compiledTemplate); $CssInline->setCSS(file_get_contents($this->settings['templatePath'] . $this->style)); $this->_compiledTemplate = $CssInline->convert(); return true; }
/** * Converts all css to inline styles * * @param string $html * * @return string */ private function cssToInlineStyles($html) { $cssToInlineStyles = new CssToInlineStyles(); $cssToInlineStyles->setHTML($html); $cssToInlineStyles->setUseInlineStylesBlock(true); return (string) $cssToInlineStyles->convert(); }