01 January 2011

How To Send HTML Emails Using Php

Many a times we want to send html emails from php. For example when a user is registered to our website and we want an automatic welcome email to be sent to the user each time or we want to notify users of any changes in the website and etc. For this purpose I wrote a very simple php script which is capable enough to send html templates as email.

Php Script

<?php
$headers = "Content-type: text/html; \n";
$to="test@example.com"; //Receiver email address
$from="no-reply@skills2earn.com"; //Sender email address
$sub="Test html email"; //Subject of the email
//Put your html template in the $template variable
//Don’t forget to include escape strings before each " or '.
$template= "<table width=\"400\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\">
<tr>
<td colspan=\"2\">Test HTML Email
</tr>
<tr>
<td>test html email
<td>test html email
</tr>
<tr>
<td>test html email
<td>test html email
</tr>
<tr>
<td colspan=\"2\">This is a test html email.
</tr>
</table>";
$headers.='From: '.$from . "\r\n" .
'Reply-To:'.$replyto. "\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($to, $sub, $template, $headers))  
echo "Mail sent successfully";
else echo "Mail sending failed";
?>

Ok guys that’s it, if you have any problem in sending html emails feel free to comment on this post.

Note: This code cannot be tested on localhost or free hosting.

No comments: