Send attractive HTML email using PHP


PHP mail() function is used to send email and this function requires some parameters to send successful email.

mail() function is one of the core functions PHP used to send email from PHP script and its very easy.

If you wanted to send newsletters, automated emails, user registration mail or any such things then you can use this mail function to do it. You can send beautiful HTML email to users.

below is syntax of mail() function.

toRequired. Specifies the receiver of the email
subjectRequired. Specifies the subject of the email. Note: This Should be a single line.
messageRequired. Defines the message to be sent.
headersOptional. Specifies additional headers, like From, Cc, and Bcc.


  • The content-type header is required to sending HTML email.
  • The additional headers are used for adding From, Cc, Bcc, etc.
  • $htmlContent variable holds the HTML contents of the email.

$to = ''; 
$from = ''; 
$fromName = 'SenderName'; 
$subject = "Send attractive HTML email using PHP"; 
$htmlContent = ' 
        <title>Send Mail</title> 
        <h1 style="text-align: center;">Hello Sir/Mam,</h1> 
        <table cellspacing="0" style="width: 80%;margin: 0% 10%;"> 
            <tbody><tr style="background: #f2f2f2;"> 
                <th style="padding: 10px;">Name:</th><td>Username</td> 
            <tr style="background-color: #e0e0e0;"> 
                <th style="padding: 10px;">Email:</th><td></td> 
            <tr style="background: #f2f2f2;"> 
                <th colspan="2" style="padding: 20px;">This is an example of PHP Send mail function</th>
            	<td colspan="2">
            		<img src="" style="width: 100%;">
 // Get HTML contents from file 
// $htmlContent = file_get_contents("email_template.html");
// Set content-type header for sending HTML email 
$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
// Additional headers 
$headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n"; 
$headers .= 'Cc:' . "\r\n"; 
$headers .= 'Bcc:' . "\r\n"; 
// Send email 
if(mail($to, $subject, $htmlContent, $headers)){ 
    echo 'Email has sent successfully.'; 
   echo 'Email sending failed.'; 

Above Example, code sends HTML email to recipient And this HTML email has inline styles for beautification.

Send HTML mail from file

Using HTML contents code within PHP code is not manageable for large size of HTML content emails.

So that we can use separate HTML file for our email HTML contents and this method is very helpful when we wanted to send dynamic mail to users.

To use separate HTML file for email first we will create HTML file with content of the message(HTML_email_Template.html).

and then Use file_get_contents() function to get contents of HTML file that we have created.

// Get HTML contents from file 
$htmlContent = file_get_contents("HTML_email_Template.html");

Leave a Reply

Your email address will not be published. Required fields are marked *