We help IT Professionals succeed at work.

PHP mail script not sending in HTML format

Brad Bansner
Brad Bansner asked
I have a PHP script that receives some incoming POST data to build a message. The message is sending, but not in HTML format. I receive the HTML code as text in the message, rather than an HTML-encoded mail message. I got most of this code from php.net, is there something I'm not doing quite right?


	$msg='<html><head><title>Liever, Hyman & Potter</head></html><body>' . $_POST['msg'] . '</body></html>';
	$headers='MIME-Version: 1.0' . '\r\n' . 'Content-type: text/html; charset=iso-8859-1' . '\r\n' . 'From:' . $_POST['sender'];

	mail($recipient, $subject, $msg, $sender);
	echo 'Mail Sent.';


Open in new window

Thank you!
Watch Question

Top Expert 2010
I strongly suggest you to use PHPMailer (http://phpmailer.worxware.com/): it solves all problems easily

  $mailer = new PHPMailer();
  $mailer->IsSMTP(); // set mailer to use SMTP
  $mailer->Host = "mail.domain.com";
  $mailer->SMTPAuth = true;
  $mailer->Username = 'username';
  $mailer->Password = 'password';

  $mailer->SetFrom('myemail@email.com', 'Me');
  $mailer->AddAddress('to@email.com', 'You');
  $mailer->Subject = $Subject;
  if (!$mailer->Send()) {
    echo "Some problem occurred!";
    echo "Email sent!";

In your particular example you need to be careful when you use single quotes and double quotes.

$headers='MIME-Version: 1.0' . '\r\n' . 'Content-type: text/html; charset=iso-8859-1' . '\r\n' . 'From:' . $_POST['sender'];

The single quotes around '\r\n' will add a literal \r\n to your $headers variable.  You need to use double quotes like this:  "\r\n" to have those translated into carriage return and line feed.

but, like MarqusG said, use a PHP mail class that already takes care of all of the headaches - you just need to call it properly.
Brad BansnerWeb Developer


Thanks for your help. Yes, the quotes were part of the problem. I also put $sender in the mail command when I should have put $header. AND I was missing the closing </title> tag. Sorry, that was really sloppy... I normally program in ASP so PHP isn't my thing. Thank you!
Dave BaldwinFixer of Problems
Most Valuable Expert 2014

First, you not sending the 'headers'.  On http://us3.php.net/manual/en/function.mail.php , it shows the proper format to be:  mail($to, $subject, $message, $headers);

Second, your message format is not correct or complete for 'proper' HTML Multipart email.

@marqusG's suggestion to use PHPMailer is a good idea though the current page for it is http://code.google.com/a/apache-extras.org/p/phpmailer/downloads/list

Explore More ContentExplore courses, solutions, and other research materials related to this topic.