views:

75

answers:

1

I am attempting to send an HTML email from a symfony (1.4.6) task, I don't want to send the entire rendered HTML output from a particular module/action, so I am rendering a partial. That's all fine, the issue is that the partial contains CSS references.

Is there a nice 'symfonic' way of including a CSS file in an HTML email from a symfony task, when all I am doing is rendering a specific partial? Or is the only solution to build the HTML head/body manually inside the task, using file_get_contents(cssFile) to grab the CSS file and then concatenating the rendered partial?

Any thoughts would be appreciated.

A: 

I ran into the same problem in my project. Here's how I fixed it:

  1. To keep the CSS separate but get it inline before sending the email, we use Emogrifier. Download the source code and put it into %sf_lib_dir%/vendor/emogrifier.

  2. Create a myMailer class that extends sfMailer. Mine is below. There are a few separate functions, but the key function is composeAndSendPartial, which takes a partial name (as a string), inserts all the CSS inline, and sends it. I tried to remove all code that's specific to my project, but I may have left some in. Let me know if it doesn't work for you or if you have any questions.

  3. In factories.yml, set the mailer: to myMailer

myMailer.class.php:

<?php
class myMailer extends sfMailer
{
  /**
   * Creates a new message with 2 bodies:
   * * 1 with $body and MIME type text/html.
   * * 1 with $body and tags stripped with MIME type text/plain. Stipped <br/>, </p>, and </div> tags and replaced with \n
   *
   * @param string|array $from    The from address
   * @param string|array $to      The recipient(s)
   * @param string       $subject The subject
   * @param string       $body    The body
   *
   * @return Swift_Message A Swift_Message instance
   */
  public function composeAndSendHtml($from, $to, $subject, $body)
  {
    return $this->send($this->composeHtml($from, $to, $subject, $body));
  }


  /**
   * Sends a message using composeHtml.
   *
   * @param string|array $from    The from address
   * @param string|array $to      The recipient(s)
   * @param string       $subject The subject
   * @param string       $body    The body
   *
   * @return int The number of sent emails
   */
  public function composeHtml($from = null, $to = null, $subject = null, $body = null)
  {
    return Swift_Message::newInstance()
      ->setFrom($from)
      ->setTo($to)
      ->setSubject($subject)
      ->addPart($this->createPlainTextBody($body), 'text/plain')
      ->addPart($body, 'text/html');
  }


  /**
   * Attempts to create a plaintext message with all html tags stripped out and new lines inserted as necessary
   * @param $body
   * @return $body
   */
  public function createPlainTextBody($body)
  {
    $body = preg_replace('/\<br\s*\/?\>/i', "\n", $body); //replace all <br/s> with new lines
    $body = preg_replace('/\<\/p\s*\>/i', "</p>\n\n", $body); //append 2 newlines to the end of each </p>
    $body = preg_replace('/\<\/div\s*\>/i', "</div>\n\n", $body); //append 2 newlines to the end of each </div>
    $body = strip_tags($body); //strip all tags from the body
    return $body;
  }

  /**
   * Composes and sends an email with a body from rendering $partial with $parameters
   * @param string $from
   * @param string $to
   * @param string $subject
   * @param string $partial the partial as a string. Feel free to change the default module name below
   * @param array $parameters Parameters for the partial
   * @param array $globalStylesheets The stylesheets that are included globally (usually global.css, maybe others)
   */
  public function composeAndSendPartial($from, $to, $subject, $partial, $parameters = array(), $globalStylesheets = array())
  {
    require_once(sfConfig::get('sf_lib_dir') . '/vendor/emogrifier/emogrifier.php');

    $context = sfContext::getInstance();
    $response = $context->getResponse();
    $originalStylesheets = $response->getStylesheets();

    if (false !== $sep = strpos($partial, '/'))
    {
      $moduleName   = substr($partial, 0, $sep);
      $templateName = '_' . substr($partial, $sep + 1);
    }
    else
    {
      $moduleName = 'email';
      $templateName = '_' . $partial;
    }

    sfConfig::set('sf_is_email', true);
    $view = new sfPHPView($context, $moduleName, $templateName, ''); #not sure what 4th parameter does
    $view->getAttributeHolder()->add($parameters);
    $view->setDecorator(true);
    $view->setDecoratorTemplate('email.php');
    $html = $view->render();
    sfConfig::set('sf_is_email', false);

    $emailStylesheets = array_keys(array_diff_key($response->getStylesheets(), $originalStylesheets));

    $css = '';
    foreach($globalStylesheets as $globalStylesheet)
    {
      $css .= file_get_contents(sfConfig::get('sf_web_dir') . '/css/' . $globalStylesheet . '.css');
    }
    foreach ($emailStylesheets as $stylesheet)
    {
      $css .= file_get_contents(sfConfig::get('sf_web_dir') . '/css/' . $stylesheet . '.css');
      $response->removeStylesheet($stylesheet);
    }

    $emog = new Emogrifier($html, $css);
    $body = $emog->emogrify();

    $this->composeAndSendHtml($from, $to, $subject, $body);
  }
}   
lyoshenka