Inline CSS for quick and dirty PHP Mailouts
One thing that ALWAYS happens to me is that I’ll get an urgent task to take an html page and send it as an email to a list of users. After about the billionth time in the last few months that I’ve had to do this, I thought I’d share a helpful snippet that makes my day…
Since, GMail, Hotmail, and Yahoo all strip ‘class=”classname”’ attributes from html tags, you can’t use your normal css tricks, so I run a little inline search-replace that extracts attributes from SIMPLE css files, and forces them to be inline eg.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# CSS File
.classname {
border:1px solid green;
background-image: url(images/ugly.jpg);
}
div.titles {
font-size: 2em;
color: #020202;
}
# HTML file
<div class="titles">
<div class="classname">
</div>
</div>
# Turns into...
<div style="border:1px solid green;background-image: url(images/ugly.jpg);">
<div style="font-size: 2em;color: #020202;">
</div>
</div> |
It doesn’t fix everything, but, its saved my butt on too many occasions to not share :)
Here is the function. Feel free to make it more robust, but, remember, move your css inline if you want the best results and check it before you send it!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$html = file_get_contents("sample.html"); $css = file_get_contents("sample.css"); mail("test@domain.com","Testing html inline",merge_html_and_stylesheet($html,$css),"Content-type: text/html\r\n"); function merge_html_and_stylesheet($html,$css) { $contents = $html; // Extract some classes (we are ignoring ids, or complicated rules for now preg_match_all("/\.([a-zA-Z0-9]+)\s+{([^}]*)}/m", $css, $matches); $styles = array(); for($i = 0; $i < count($matches[0]); $i++) { $styles[$matches[1][$i]] = $matches[2][$i]; } // Replace classes with inline styles preg_match_all("/class=\"([a-zA-Z0-9]+)\"/", $contents, $matches); $cache = array(); for($i = 0; $i < count($matches[0]); $i++) { $contents = str_replace("class=\"" . $matches[1][$i] . "\"","style=\"" . $styles[$matches[1][$i]] . "\"", $contents); } return $contents; } |