How to style email body in php [duplicate]

2020-03-21 10:42发布

问题:

This question already has answers here:
Closed 5 years ago.

I want to style mail body. I have tried the below methods to style mail body. But all of them didn't work

1) Used external style sheet style.css

td{padding:10px;}   

mail.php

<link rel="stylesheet" href="style.css"></link><table><td>....</td></table>

2) Defined Internal Style Sheet:

mail.php

 <style type="text/css">
td{
    padding-bottom:8px;
}

</style>
<table><td>....</td></table>

I know, Inline style works by doing <td style='padding-bottom:8px'>, But i have got many tables, doing the inline style is not a good idea, Is there any work around so that no need to define style for each element

回答1:

for email, usually the safest bet is tables and inline styles (Everything you shouldn't be doing in web design).

$mailBody = '<html><body>';
$mailBody .='<table width="100%"><tr>';
$mailBody .='<td style="padding:10px"></td>';
$mailBody .='<td style="padding:10px"></td>';
$mailBody .='<td style="padding:10px"></td>';
$mailBody .='</tr></table>';
$mailBody .='</body></html>';

Sadly internal and external style sheets don't always work across different email clients.



回答2:

Typically tables are the way to go. Unfortunately to get the most widespread support you need to use inline styles. A lot do cascade so you don't have to style every element however. For example using font-family on a table element would apply it to td elements.

Campaign monitor provides a useful overview of support for CSS across the most common email clients here http://www.campaignmonitor.com/css/

Email boilerplate ( http://htmlemailboilerplate.com/ ) will also provide you with a template with which you can start and it'll teach you how to avoid a lot of the common shortcommings of many email clients.



回答3:

There is a solution. Please check this out: CSS to Inline style

There is also another library that does the same task. http://www.pelagodesign.com/sidecar/emogrifier/

Basically these libraries convert your css style rules into inline styles, so that all the email clients will render your HTML document correctly