? htmlmail.module.new
Index: htmlmail.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/htmlmail/htmlmail.module,v
retrieving revision 1.9.2.5
diff -u -p -w -r1.9.2.5 htmlmail.module
--- htmlmail.module	8 Jan 2009 06:39:18 -0000	1.9.2.5
+++ htmlmail.module	12 Jun 2009 16:29:27 -0000
@@ -46,6 +46,8 @@ function htmlmail_mail_alter(&$message) 
   if (variable_get('htmlmail_urlfilter', '1') == 1) {
     $message['body'] = _htmlmail_url($message['body']);
   }
+
+  $message['body'] = _htmlmail_emogrify($message);
 }
 
 function htmlmail_theme(){
@@ -327,3 +329,47 @@ function _htmlmail_autop($text) {
   return $output;
 }
 
+/**
+ * If the Emogrifier <http://www.pelagodesign.com/sidecar/emogrifier/> exists,
+ * the CSS styles inside the the $message['body'] are inserted into the other
+ * HTML tags within the same $message['body'] as inline style attributes, 
+ * based on CSS selectors.
+ *
+ * This function is based on code in the simplenews_template module.
+ *
+ * This emogrifier differs from that of simplenews_template in that it permits
+ * modules or users to adjoin CSS into the $message['body'] using the HTML 
+ * <style> tag.  The function searches the entire body for style tags, 
+ * concatenates them in order of appearance in the file, then sends them to
+ * the Emogrifier script. 
+ *
+ * Note that the method modifies the $message['body'] directly, and the 
+ * return value is the modified $message['body'] string as well. 
+ *
+ *
+ * @param $message
+ *           The message array to be sent. This function works directly 
+ *           on the $message['body'].
+ * @return $message['body']
+ *           The modified message body string with inlined CSS applied.
+ */
+function _htmlmail_emogrify(&$message) {
+  $path = drupal_get_path('module', 'htmlmail');
+  $path = "./$path/emogrifier.php";
+  if (is_file($path)) {
+    $style = array();
+    //Pull out the contents of any style tags
+    if(preg_match_all("@<style[^>]*>(.*)</style>@Usi", $message['body'], $matches, PREG_PATTERN_ORDER)) {
+      $style = $matches[1];
+    }
+    // Emogrify can't handle several CSS rules on one line. As a precaution,
+    // we therefore insert LF after each closing bracket.
+    $style = preg_replace('/}\s*/', "}\n", implode("\n",$style));
+
+    // Inline the CSS rules.
+    include_once $path;
+    $emogrifier = new Emogrifier($message['body'], $style);
+    $message['body'] = $emogrifier->emogrify();
+  }
+  return $message['body'];
+}
