Send HTML email including CSS style sheet via PHP

34,518

Solution 1

Google, Outlook, Yahoo all the major email service providers do not allow CSS external files. It may sound antiquated that they have opted for inline styles and tables to render a proper email message with any styling.

It may be tedious to code but companies like https://litmus.com/ and envato will help with some templates and formatting issues.

my 2¢'s: email providers can't trust all sources of information being sent and so this is a way of keeping the malicious code at bay.

Solution 2

It would be best to just put a <style> block with all the CSS inside it somewhere in the index.html body. Some email clients/portals cut all the CSS embedded in the header with <link rel="stylesheet" type="text/css" href="..." >. As a result not using inline CSS may cause your emails to appear 'broken' or simply look bad on accounts with @gmail.com for example.

Solution 3

Within your index.html file, include a <style> tag as below.

<style>
.class{
style: attribute; 
}
</style>";

That should work, if not then I may recommend hosting your stylesheet on a website and including a <link> tag similar to the one below in the head of your index file

<link rel='stylesheet' type='text/css' href='http://www.yourstylesheet.com'>";

Either of those methods should help with your problem.

Share:
34,518
Wijden
Author by

Wijden

Updated on July 04, 2020

Comments

  • Wijden
    Wijden almost 4 years

    I want to send a HTML page that contains CSS stylesheet to an email account. The problem is that the CSS style sheet is not visible at all. Do I have to inline every CSS styling? It seems to be highly inefficient method. Any others ideas ?

    Below is the PHP code for sending the email :

    <?php
    $to = "[email protected]";
    
    // subject
    $subject = "Test mail";
    
    // message
    $message = file_get_contents("index.html");
    
    // from
    $from = "[email protected]";
    
    // To send HTML mail, the Content-type header must be set
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    
    // Additional headers
    $headers .= "From:" . $from;
    
    // Mail it
    mail($to,$subject,$message,$headers);
    
    echo "Mail Sent.";
    ?>
    

    I would greatly appreciate your help. Thanks in advance.

  • rybo111
    rybo111 over 8 years
    Inline CSS is recommended, because not all mail clients support CSS in the <head>.
  • Imnotapotato
    Imnotapotato almost 8 years
    will this work the same with a js code? (jQuery and a js library)
  • Karthi
    Karthi over 7 years
    in case if i am use bootstrap means how can i add css? or if i add all the css in inline format ??
  • Roman
    Roman over 7 years
    Yes, add it inline.