If you are sending mail with Html content then it’s really a tough task for us to add css on each element. Some times we add it manually, we tried to add classes in head section or even in body or some dev use <link ..> in there mail content 🙂 and feel surprised, what happened, why it didn’t work.
Lets take a deep breath and see why some of top mail services like Google are laughing at us. Simply, emails are just different side of dice, you can not just treat your mail like webpages.
So from that link you can understand mostly methods fails at time of sending mail even head/ body styles too (in Google) so one way to do this is inline css method, just add css to each element but is it really possible ? if you are creating mails dynamically. Let me think if customers are creating templates but without knowledge of html/ css then ?
To solve this problem we can use various php library, which are freely available in Open Source World like InlineStyle, Emogrifier (Magento uses this to add css in templates V2)
How to use Inline Style Class (it used Symfony Class to convert, if you want independent library then try Emogrifier)-
use namespace to use this file.
use \InlineStyle\InlineStyle;
Then create an object of InlineStyle class with Html content.
$html = new InlineStyle('<p class="text-success">Green Content</p>');
or you can get content from url
$html = new InlineStyle(file_get_contents("http://webkul.com"));
Now we will add css using object so that this library can add css to our added Html. We can add css from 2 ways
1st – First we can add css in Html content and then extract it using our created object and then apply.
$html->applyStylesheet($html->extractStylesheets());
2nd – Apply css from external link
$html->applyStylesheet(file_get_contents("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"));
All set, now time to get our converted object.
$convertedHtml = $html->getHTML(); //<p style="color: #3c763d" class="text-success">Green Content</p>
One more thing if you are getting error realetd to /DOMDocument parsing then add this line to your InlineStyle Constructor
libxml_use_internal_errors(true);
Framework used Symfony2.
Be the first to comment.