embedding HTML in an email sent with PHP

Posted on 2011-05-02
Last Modified: 2012-05-11
Does anyone have some information on how to include some HTML in an email sent by PHP?  Or maybe the whole email needs to be HTML.  That would be ok.  

Also, does anyone have any information on the percentage of  people who are able to read HTML in a received email?

Thanks for any info.
Question by:steva
    LVL 22

    Accepted Solution

    check the following link for examples:
    LVL 15

    Assisted Solution

    by:Jagadishwor Dulal

    Author Comment

    Thanks guys for the great references!  The second reference mentions two problems with HTML email are poor security and the possibility that it might be more apt to get caught in a spam filter.  But no one mentioned the possibility that some recipients might not be able to read HTML emails.  Am I being silly to worry about this?
    LVL 82

    Assisted Solution

    What you need to do is send an multipart/alternative email. Basically you will write TWO bodies  - TWO copies of the main message. One of them will be your plain text, the other will be your HTML version.  The user's email client/program will read whatever it is they can interpret.

    I suggest you get the phpmailer class. It makes this task extremely simple.

    The "Alternate Text Bodies For HTML Mail" section on the following link shows the basic syntax to achieve this:

    Refer to the 6th post at the following link for a complete example:

    You can download this class from:

    Lastly, on that site you can find several examples at:
    Products > PHPMailer > PHPMailer Examples

    LVL 11

    Expert Comment

    You can use phpmailer classes which provides html template seperate files search for phpmailer library
    LVL 107

    Assisted Solution

    by:Ray Paseur
    I have done this in a native form and also with PHPMailer.  There are so many layers to the answer and so many trip-wires involved in email, that I would recommend that you simply skip the part about trying to do it yourself and use a service like Constant Contact instead.  They have full-time professionals at work on the problems that you will have to face if you try to do this yourself.  Some of the issues they will handle for you...

    Avoiding the legal liability that puts you at risk of criminal penalties involving handcuffs and prison if you send, even accidentally, unsolicited commercial email
    Handling the spam filters (an ever-changing maze of legitimate and completely off-the-wall "rules" for detecting spam)
    Creating messages that render correctly in all email reader programs, no two of which render HTML exactly alike
    Providing feedback - who opened the messages, who forwarded the messages, etc
    Providing statistics that summarize the individual message feedback in neatly ordered tables and graphs
    Providing for automatic subscription and removal, a Federal compliance issue
    Making surveys and reservations an easy part of your email campaigns

    ... and more.  There are competitors to but they are among the best and they are embarrassingly inexpensive.  Give them a look before you waste too much time trying to do this yourself.  Since 2008 I have not added new "home-grown" email functionality to any client web site and I have moved several sites to Constant Contact.  The results have been uniformly excellent and it has saved me countless non-value-added hours that were previously given over to dealing with email issues.  Best regards, ~Ray
    LVL 5

    Assisted Solution

    This uses mail() to send the email, along with attachments and HTML. very simple too.
    function send_mail($emailaddress, $fromaddress, $emailsubject, $body, $attachments=false)
      # Common Headers
      $headers .= 'From: '.$fromaddress.''.$eol;
      $headers .= 'Reply-To: '.$fromaddress.''.$eol;
      $headers .= 'Return-Path: '.$fromaddress.''.$eol;    // these two to set reply address
      //$headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
     // $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters
      # Boundry for marking the split & Multitype Headers
      $headers .= 'MIME-Version: 1.0'.$eol;
      $headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol;
      $msg = "";      
    // Add a multipart boundary above the plain message
     $msg = "This is a multi-part message in MIME format.\n\n" .
                "--{$mime_boundary}\n" .
                "Content-Type: text/html; charset=\"iso-8859-1\"\n" .
                "Content-Transfer-Encoding: 7bit\n\n" .
                $body . "\n\n"; 
      if ($attachments !== false)
       for($i=0; $i < count($attachments); $i++)
         if (is_file($attachments[$i]["file"]))
           # File for Attachment
           $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
           $handle=fopen($attachments[$i]["file"], 'rb');
           $f_contents=fread($handle, filesize($attachments[$i]["file"]));
           $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
           # Attachment
           $msg .= "--".$mime_boundary.$eol;
           $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;
           $msg .= "Content-Transfer-Encoding: base64".$eol;
           $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
           $msg .= $f_contents.$eol.$eol;
      //ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
      mail($emailaddress, $emailsubject, $msg, $headers);
      $headerss .= 'From:'.''.$eol; 
     // mail('', 'kk', 'ksk', $headerss);
      echo "mail send";
    # To Email Address
    # From Email Address
    $fromaddress = "Name <>";
    # Message Subject
    $emailsubject="Re: awesome!";
    # Use relative paths to the attachments
    $attachments = Array(
      Array("file"=>"10_094.jpg", "content_type"=>"image/jpeg"),
      Array("file"=>"09_062.jpg", "content_type"=>"image/jpeg")
      //Array("file"=>"../../test.doc", "content_type"=>"application/msword"),
     // Array("file"=>"../../123.pdf", "content_type"=>"application/pdf")
    # Message Body
    $body="Thisrtyuioyuioyuityui is a message with <b>".count($attachments)."</b> attachments and some <i>HTML</i>!";
    send_mail($emailaddress, $fromaddress, $emailsubject, $body, $attachments);
    echo $emailaddress;

    Open in new window


    Author Closing Comment

    So many great comments.  So few points to award.


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
    Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now