Sending html emails using php

In this tutorial you will learn how to send html emails in php. Nowadays it is common requirement in almost every website to have contact us form or feedback form, user fill that form and email is generated to concern person.
To improve the performance, it is strongly recommended to send email in html format because it is more easy to read and understandable.

Send html emails using php

function send_email($from, $to, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n"; 
//set content type to HTML 
$headers .= "Content-type: text/html\r\n"; 

if ( mail($to,$subject,$message,$headers) ) 
{
header("location:yourdesirepage.php?msg=sent");

} 
else 
{
header("location:yourdesirepage.php?msg=notsent");
}
}

$from_email="fromyou@gmail.com";
$to_email="tosomeone@gmail.com";
$subject="Subject of Email";
$message.="<html><body>";
$message.="<strong>Your message here will be look bold when visible to reader</strong>";
$message.="Some more message";
$message.="</body></html>";
send_email($from_email,$to_email,$subject,$message);



To send html email I have written a custom function send_email() that takes four parameters and then i made a call to built-in mail() function in it to send email.


$headers is a variable containing all the headers of the email, using this variable html email will be sent to the user. Let's have a look over the code of $headers line by line


$headers = "From: ".$from."\r\n";



From header contains the email address used for sending email.
$headers .= "Reply-To: ".$from."\r\n";

Reply-To header contains the information of email address where replies should be sent.


$headers .= "Return-Path: ".$from."\r\n";

Return-Path contains the return path of the email.It is same as the Reply-To header. Some email clients require this, others create a default.
$headers .= "Content-type: text/html\r\n"; 

Now this above line of code gives you the ability to send html emails, if we use Content-type:text/html then its mean we can send email of both text and html format.


Note:-Header names are case sensitive. Each header is ended with the Return and Newline characters \r\n. There are no spaces among header name.
So that's it.


Happy coding!!!

0 comments: