Sending HTML E-mail Using PHP

Stephen Yagielowicz

Not too long ago there was a discussion about the pros and cons of having a message board on a pay site as a means of increasing customer interactivity, feedback, and retention. In this enlightening discussion was overlooked another, perhaps simpler and yet more practical and effective tool - the newsletter.

An informative, helpful, entertaining, and attractive newsletter (especially an HTML-formatted one) can be a tremendous asset to any e-commerce enterprise. Successfully producing and delivering one is a process not without its share of concerns and considerations, however.

Beyond the dynamics of producing compelling content for a newsletter, there are a handful of technical requirements that are occasionally problematic to overcome, depending upon your hardware and software infrastructure and configuration. One way to make the process run smoother is to send HTML-formatted mailings through a PHP gateway script that comes pre-configured with the necessary headers and other required information.

Valentin Ciocea from Ciocea Soft was kind enough to send us a PHP script that pre-configures your e-mail headers, then pulls an HTML file (in this case "newsletter.html") from your hard drive, and then sends it to the designated list of recipients.

Just don’t forget to use absolute references (such as <IMG src=>) to included objects when building your HTML page.


// read the HTML newsletter from hard drive :
$html=fread($fis,filesize ($path."newsletter.html"));

$subject="Here is your newsletter.";

//add From: header
$headers = "From: $sender\r\n";

//specify MIME version 1.0
$headers .= "MIME-Version: 1.0\r\n";

//unique boundary
$boundary = uniqid("HTMLDEMO");

//tell e-mail client this e-mail contains//alternate versions
$headers .= "Content-Type: multipart/alternative" .
"; boundary = $boundary\r\n\r\n";

//message to people with clients who don't
//understand MIME
$headers .= "This is a MIME encoded message.\r\n\r\n";

//plain text version of message
$headers .= "--$boundary\r\n" .
"Content-Type: text/plain; charset=ISO-8859-1\r\n" .
"Content-Transfer-Encoding: base64\r\n\r\n";
$headers .= chunk_split(base64_encode("This e-mail contains the newsletter, but you are unable to see because it is in HTML and your email client can't display it."));

//HTML version of message
$headers .= "--$boundary\r\n" .
"Content-Type: text/html; charset=ISO-8859-1\r\n" .
"Content-Transfer-Encoding: base64\r\n\r\n";
$headers .= chunk_split(base64_encode($html));

//send message
mail($receiver, $subject, "", $headers);


Of course, YOU need to build the HTML page that you want to use for your mailing, and have a proper opt-in mail list as well, but we’ll give you this fully-comented e-mailing script to help get you started. If you have trouble with this script, contact your server admin, or Valentin, or ask about it on XBiz' Coder's Underground message board. Good Luck! ~ Stephen