Email with HTML

Written by: Sharath Shambu | December 18th, 2015

Category: Email, HTML, Php

Introduction There are times when we would want to send interesting Emails to our users rather than just plain old text Emails. Even though there is quite a simple solution for this, I wasted a good number of hours trying to achieve this. So how do we do this?? I learned this the hard way Embedding HTML in your Email body is as straight forward as sending Emails with text content. Lets take a simple example.

 $to = '';

$subject = 'Welcome to XYZ!';

$from = '';

// To send HTML mail, the Content­type header must be set

$headers  = 'MIME­Version: 1.0' . "\r\n";

$headers .= 'Content­type: text/html; charset=iso­8859­1' . "\r\n";

// Create email headers

$headers .= 'From: '.$user_email."\r\n".

    'Reply­To: '.$user_email."\r\n" .

    'X­Mailer: PHP/' . phpversion();

// Compose a simple HTML email message

$message = '<html><body>';

$message .= '<h1>Hi John Doe!</h1>';

$message .= '<p>We hope you enjoy using our product.</p>';

$message .= '</body></html>';

// Sending email

if(mail($to, $subject, $message, $headers)){

    echo 'Email Sent!!';

} else{

    echo 'Email sending failed. Please try again.';


Now, all we are doing here is sending an Email to our friend. In Spite of embedding HTML, it’s not of much use if we can’t style it. So you would think, why not just put the style rules in our <style> tags?? Well, that’s how it is we can’t use classes when embedding HTML. But, guess what? We can write our CSS rules inline. Let’s take the same example with some nice styling.
 $message = '<html><body>';

$message .= '<h1 style="font­size: 25px">Hi John Doe!</h1>';

$message .= '<p style="color: blue">We hope you enjoy using our 


$message .= '</body></html>';

The extent of styling is up to you. You can also embed images in Emails and I don’t mean as attachments. To do that you need a public URL of the image.
 $message = "<html><body>";

$message .= "<h1 style='font­size: 25px'>Hi Firend!</h1>";

$message .= "<p style='color: blue'>We hope you enjoy using our 


$message .= "<p>We have some exciting discounts for your next 


$message .= "<div style='text­align:center;'>";

$message .= "<img style='display: inline­block; width: 200px; height: 200px;' 


$message .= '</div>';

$message .= '</body></html>';

That’s it. We just learned how to send out nice looking Emails. You can also use this lightweight library to ease your work.

Leave Comment

We would love to hear from you and we appreciate the good and the bad.