PHP: Send HTML Email (mail)

by Yang Yang on April 23, 2009

in HTTP Tips & Tutorials, PHP Tips & Tutorials

Share This Article:
Subscribe to Kavoir: blog feed

As we all know the simplest approach to create an email message and send it out is to use the php mail() function. A typical usage example would be:

mail('recipient@email.com', 'Subject Title', 'Message body goes here.');

However, as the mail() function sends emails in text/plain mime type by default, if you include HTML code in the message body, it would not be interpreted as HTML at all. Instead, all the tags and attributes are displayed as they are.

To work around this and send HTML email with PHP mail() function, you will have to modify the message mime type to text/html. In practice, use the mail() function with an additional argument to set arbitrary headers for the email message:

$to = 'recipient@email.com';
$subject = 'Purchase Successful!';
$message = '
<html>
<head>
	<title>Purchase Successful!</title>
</head>
<body>
	<p>Here are the order details:</p>
	<p> ... </p>
	<p><a href="http://www.example.com">back to store</a></p>
</body>
</html>
';

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

mail($to, $subject, $message, $headers);

Now the email dispatched to the recipient will have all the HTML in it working as expected.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 2 comments… read them below or add one }

Yasitha Dinushi October 18, 2010 at 3:06 pm

Hi, can i send html emails with attachments

Reply

Yang Yang October 19, 2010 at 4:24 pm

Absolutely.

Seems to me you have read the post here: http://www.kavoir.com/2009/08/php-email-attachment-class.html

Reply

Leave a Comment

Previous post:

Next post: