Send HTML email with PHP

This tutorial will guide you to how to write PHP script to send email with HTML format. Rather than ordinary old-fashion text format, HTML email are more attractive, this is good if you want to impress or attract your customer.

The PHP function to send email is mail() function. Below is the mail’s function description from the PHP manual:

mail() -- send mail

Description
bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]])

mail() automatically mails the message specified in message to the receiver specified in to. Multiple recipients can be specified by putting a comma between each address in to. Email with attachments and special types of content can be sent using this function. This is accomplished via MIME-encoding.

mail() returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.

Sending email is very simple as 1 2 3, here is the example :

<?php
mail("user@hostcom", "Hello Subject", "Hello, this is test from php script", "From:youruser@yourhost.com");
?>

The 4th parameter are needed if you not set default email from in your php.ini setting. Actually you can make funny things here, such as act were this email came from Bill Gates ? hehehe

<?php
mail("yourfriend@mailhost.com", "Hello There !", "Hello, You are not using the original copy of windows operating system !", "From:billgates@microsoft.com");
?>

Try it, you might chuckling at your self.

Sending a HTML email actually very simple, you just need a HTML code in your mail body, and the most important is you need to set content header and which character set will be use

Content-type: text/html; charset=iso-8859-1

More on this you can add the Carbon Copy (CC:), Blind Carbon Copy at the email headers

<?php

/**
 * @author sapta
 * @copyright 2009
 */

/* set recipients, from, CC:, BCC: */
$to  = "mary@example.com" . ", " ; // note the comma
$to .= "kelly@example.com";

$from = 'your.user@mailhost.com';
$cc = 'friend1@somehost.com, friend2@somehost.com';
$bcc = 'your.friend@blindhost.com';

/* set subject */
$subject = "Hi, test PHP mail";

/* message */
$message = '
<html>
<head>
<title>Test PHP eMail</title>
</head>
<body>
<h1>Hello !</h1>
<p>Hi guys, check this out, i can send a HTML message with PHP !!</p>
</body>
</html>
';

/* To send HTML mail, you need to set the Content-type header. */
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

/* additional headers */
$headers .= "To: ".$to."\r\n";
$headers .= "From: ".$from."\r\n";
$headers .= "Cc: ".$cc."\r\n";
$headers .= "Bcc: ".$bcc."\r\n";

/* finally, mail it! */
mail($to, $subject, $message, $headers);

?>

Ok, that’s it, try this out, let me know if you had a question.

Related posts:

  1. Validasi Form menggunakan Javascript

Leave a Reply