• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 267
  • Last Modified:

embedding HTML in an email sent with PHP

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.
5 Solutions
Om PrakashCommented:
check the following link for examples:
Jagadishwor DulalBraces MediaCommented:
stevaAuthor Commented:
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?
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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

You can use phpmailer classes which provides html template seperate files search for phpmailer library
Ray PaseurCommented:
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 ConstantContact.com 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
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: email@server.com'.''.$eol; 
 // mail('email@server.com', 'kk', 'ksk', $headerss);
  echo "mail send";
# To Email Address

# From Email Address
$fromaddress = "Name <email@server.com>";

# 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

stevaAuthor Commented:
So many great comments.  So few points to award.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now