Saturday, September 12, 2015

PHP Send html email

PHP has an inbuilt functionality to send email.
We can send email in php using the mail function.
The following function uses the inbuilt mail function to php to send email but in HTML format.
HTML emails are popular nowadays and almost 90% of the websites uses this features to send HTML emails to their customers.

function sendHTMLemail($HTML,$from,$to,$subject,$cc='')
{
// First we have to build our email headers
// Set out "from" address
$headers = "From: $from\r\n";
if($cc!='')
$headers.= "CC: $cc\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);
}

 The function can be used as follows:

$HTML = "Hello John, <br /> How are you Today? <br /> Thanks!";
$from= = "Your email id here";
$to = "Email address of the person to whom you want to send the email";
$subject = "Test Email";
$cc = 'Email of the person to whom you want to keep in CC';

sendHTMLemail($HTML,$from,$to,$subject,$cc);

No comments:

Post a Comment

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...