Send an HTML email using PHP

Posted on Posted in Blog

Veba Software recently had a programming project that requires a script to email some trending data to the owner. Although the script isn’t really complicated, presenting it in a viable manner was a headache. We can’t just send the email as a pure text else, we’d end up confusing the owner.

The very first thing that came to our minds was to send the email as an HTML using tables to present the data. We felt that presenting the data in table form is easily understood than text.

Here is a sample data which we intend to send to the owner via email:

[php]
array (“before” => 103,
“now” => 125,
),
“Thailand” => array (“before” => 86,
“now” => 102,
),
“Philippines” => array (“before” => 16,
“now” => 23,
),
);
?>
[/php]

Basically, its some trending data to be presented in three columns, the first being countries; the second the “before” value; and the third the “now” value. This is just an example and the values that you could be using here may come from the database.

Let us present the data in table form and expect that this is how it should look like when sent as an email.

[php]
$content = “

n”;

foreach ($data as $key=>$dat){
$content .= “

n”;
}
$content .= “

Countries Before Now
$key {$dat[‘before’]} {$dat[‘now’]}

“;
[/php]
Table for the above snippetYou may notice that the above snippet has tables with embedded styling properties. Some email clients (mostly the browser based ones) get rid of CSS styles to prevent HTML emails from overriding their CSS hence, the embedded styles in each tag.

The table when presented should look like the image in the left.

Now how are we going to send the “html” as an email? The answer is to send the email using the mail() function of PHP and alter the header part of the mail() function.

[php]
$recepient = ‘myemail@website.com’;
$headers = ‘MIME-Version: 1.0’ . “rn”;
$headers .= ‘Content-type: text/html; charset=iso-8859-1’ . “rn”;
$headers .= ‘To: ‘ . $recepient . “rn”;

$subject = “Data Report”;

mail ($recepient, $subject, $content, $headers);
[/php]

The $recepient variable in the above script is where the email should be sent (needs to be a valid email address). The key to presenting the email as an HTML is on the header, particularly the Content-type part – which in this case is text/html.

So there you go – another “how to” in PHP brought to you by veba-software.