|
|
Sending a simple text based email via PHP is very easy thank to the provision of the mail() function.
However, if you want send a HTML formatted email, things get a little more complicated. The great thing about the mail function is that it allows you to generate your own email headers. This headers can be a little confusing, however, once you have got a wrapper function things become a lot easier.
So what we have created here is a custom function sendHTMLemail. You pass the function the HTML code, the from and to address and the subject line. The function sends one email contained both the HTML version and the text version.
A description of the code is in the comments. |
<?php
// Example
$HTML = "<b>This is a test</b>";
$from = "test@test.com";
$to = "this@that.com";
$subject = "I'm sending a test HTML email";
sendHTMLemail($HTML,$from,$to,$subject);
function sendHTMLemail($HTML,$from,$to,$subject)
{
// First we have to build our email headers
// Set out "from" address
$headers = "From: $from\r\n";
// Now we specify our MIME version
$headers .= "MIME-Version: 1.0\r\n";
// Create a boundary so we know where to look for
// the start of the data
$boundary = uniqid("HTMLEMAIL");
// First we be nice and send a non-html version of our email
$headers .= "Content-Type: multipart/alternative;".
"boundary = $boundary\r\n\r\n";
$headers .= "This is a MIME encoded message.\r\n\r\n";
$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(strip_tags($HTML)));
// Now we attach the HTML version
$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));
// And then send the email ....
mail($to,$subject,"",$headers);
}
?> |
|
|