我在使用PHPMailer发送HTML邮件时遇到问题.我制作了一个Smarty模板,我从中获得了所有的HTML代码,但是当我发送邮件时,我收到的邮件没有包含CSS(它只是背景颜色,字体或类似的东西).在PHPMailer中,我设置邮件是HTML.
有没有办法发送包含CSS的HTML邮件?
有一种方式......
$body = <<< YOUR_HTML_WITH_CSS_STYLE_TAGSsome htmlYOUR_HTML_WITH_CSS_STYLE_TAGS; $doc = new DOMDocument(); @$doc->loadHTML($body); $xpd = new DOMXPath($doc); 0&&$node = new DOMElement(); $result = $xpd->query('//img'); foreach($result as $node){ $attr = $node->getAttribute('src'); $re = '/(http:\/\/.*?)?(\/.*+)/i'; if(preg_match_all($re, $attr, $matches)){ if(!empty($matches[1][0])&&0) continue; $attr = 'http://'.$_SERVER['HTTP_HOST'].$matches[2][0]; } $node->setAttribute('src',$attr); } false&&$node=new DOMElement()&&$child=new DOMElement(); $result = $xpd->query('//style/..'); foreach($result as $node){ foreach($node->childNodes as $child){ if(strtolower($child->nodeName)=='style'){ $node->removeChild($child); $css = $child->textContent; $re = '/(.*?)\{([^}]+)\}/'; if(preg_match_all($re, $css, $matches)){ foreach($matches[1] as $idx=>$css_selector){ $css_text = $matches[2][$idx]; $css_text = preg_replace('/\s+/',' ',$css_text); $css = new CSSQuery($doc); foreach($css->query($css_selector) as $selected_node){ $style = $selected_node->getAttribute('style'); $selected_node->setAttribute('style', $style?$css_text:$style.';'.$css_text); } } } } } } $body = $doc->saveHTML();
该代码将在$ body中生成HTML输出,如下所示:
some html
该CSSQuery
课程可以在phpclasses.org找到.此实现基于以下事实:大多数Web邮件仅允许通过内联标记属性样式添加样式,而不是通过样式标记或链接标记.
它非常有限,并且由于正则表达式具有有限的语法,因此它很简单,但它仍然比您自己在每个HTML标记中使用内联样式属性更好.