Neil Ang


A stunning likeness of Neil Ang
Hello world

Sending HTML Emails in PHP

Posted on

Just like the general nature of PHP, the PHP mailing functions are simple to use as well. The easiest way to send an email is to use the mail function built into PHP 3, PHP 4 and PHP 5. However, to send HTML based emails (or any other content-type for that matter), you will need to alter the header values of the email. The following is a short example on how to do this with PHP.

Configure PHP.ini

To send an email, you must first check your php.ini mail settings are correct (if these setting are correct, skip down below to the code). If you are using Windows, you will need access to a SMTP server (your web host should provide you with one, otherwise you can setup your own), otherwise if your using a Mac or Linux, you will need the sendmail mail transfer agent (this is usually preinstalled with the OS).

For Windows users, locate and open your php.ini file and find the following lines:

[mail function]
; For Win32 only.
;smtp_port =
; For Win32 only.
;sendmail_from =

Add the correct settings and remove the line comment marks (semi-colons) so the configuration looks similar to this:

[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25
; For Win32 only.
sendmail_from =

For non-Windows users locate the following lines in the php.ini:

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =

Uncomment and add the full path to sendmail like this:

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = /usr/sbin/sendmail

Save and close php.ini. If you are using PHP through a web server, it might require a restart for changes to take effect.

The code

The following PHP code when executed will create a HTML message and send it to a recipient (or multiple recipients by separating each email address in the '$to' variable with a comma):


  $to = '';
  $subject = 'My Test HTML';
  $message =<<<EOM
  <body><h1>My HTML Message</h1>
    <p>This is text</p>

  $headers = 'From:' . "\r\n" . 'content-type: text/html;'. "\r\n";

  if(mail($to, $subject, $message, $headers)){
    echo 'Mail sent successfully!';
  else {
    echo 'Mail could not be sent, please check your settings.';