How to Send Email from a PHP Script

Man working outdoors at a coffee shop
john shepherd/E+/Getty Images

Sending email from a PHP script on a web page is easy.

A Screwdriver for the Web

PHP is a tool you can use to get things done quickly on the web. Sending email from a PHP script is one of those things. Without much fuss or stringency, PHP offers just the tool.

Send Email from a PHP Script

All it takes is the right configuration (to send mail using a local or a remote server) and one function:

  • mail().

Send Email from a PHP Script Example

The first argument to this function is the recipient, the second specifies the message's subject and the third one should contain the body.

So to send a simple sample message, we could use:

 $to = "";
 $subject = "Hi!";
 $body = "Hi,\n\nHow are you?";
 if (mail($to, $subject, $body)) {
   echo("<p>Email successfully sent!</p>");
  } else {
   echo("<p>Email delivery failed…</p>");

That's it! Note that you can have PHP validate email addresses for correctness before sending.

Use Custom Headers (e.g. "From:") in Mail from a PHP Script

Do you want to set a custom From: address, maybe taken from the form you send, or another custom header line? It is but an additional argument you need.

Protecting Your Script from Spammer Exploit

If you use the mail() function (in combination with a web form in particular), make sure you check it is called from the desired page and protect the form with a CAPTCHA maybe. You can also check for suspicious strings in any arguments (say, "Bcc:" followed by a number of email addresses).

Send Email from a PHP Script with SMTP Authentication

If mail() does not work for you, you have options, too. The mail() function included with stock PHP does not support SMTP authentication, for example. If mail() does not work for you for this or another reason, try the PEAR Mail package, which is much more comprehensive while maintaining, to a large degree, the simplicity and ease of mail() for sending mail from PHP.

(Updated August 2013)