1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Discuss in my forum

How to Send Email from a PHP Script

By

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

PHP seems to make most things extremely easy. Sending email from a PHP script is no exception.

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:

<?php
 $to = "recipient@example.com";
 $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)

Related Video
Create Email Aliases and Forwarding Addresses in Gmail
Gmail Labels and Filters

©2014 About.com. All rights reserved.