PHP – Send HTML Email

If you want to send HTML email using the PHP mail(), here is an example.

<?php

$to = "<recipient's email>";
$from = "<sender's email>";
$subject = 'Eureka! send html email';
$message  = '<p style="color: red;">Eureka!</p>';
$message .= '<p style="color: green;">Reference: <a href="http://eureka.ykyuen.info">PHP - Send HTML Email</a></p>';
$message .= '<p style="color: blue;">Hello World!</p>';

htmlMail($from, $to, $subject, $message);

function htmlMail($from, $to, $subject, $message) {
  $headers  = 'MIME-Version: 1.0' . "\r\n";
  $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
  $headers .= "From: $from" . "\r\n";

  // Enforce the send from email address
  $sendmail_params  = "-f$from";

  if (mail($to, $subject, $message, $headers, $sendmail_params)) {
    print 'Email sent';
  } else {
    print 'Fail';
  }
}

?>

 

You could add other parameters in the $headers such as Cc, Bcc and the reply-to email address. For more examples, please refer to PHP Manual – mail()

* Outstanding problem: I found that if the server is using Gmail relay to deliver emails, i couldn’t enforce the sender email address. please let me know if you have any idea. Thanks.

Done =)

2 thoughts on “PHP – Send HTML Email”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.