How to Send Email From a PHP Script

The PHP mail() function is a simple and easy way to send email from a PHP script running on a web page. This means you're using a Sendmail program to send emails directly from your web server rather than your mail server. Here's how it works.

You can also send email from your PHP script using SMTP authentication, specifying whether the PHP email script should use a local or remote SMTP server for sending messages.

Close-Up Of Cursor On Mail Icon
 Daniel Sambraus / Getty Images

PHP Mail Script Example

If you implement this example, make sure to change the elements that apply to you, such as your email address, subject, and message.

<?php
ini_set( 'display_errors', 1 );
error_reporting( E_ALL );
$to = "youremailrecipient@example.com";
$subject = "Your subject here";
$message = "Your message here";
echo "The email message was sent.";
?>

The first two lines allow you to see any errors that may occur with your script:

ini_set( 'display_errors', 1 );
error_reporting( E_ALL );

Next is the To line. This is the email address the email should be sent to. This could be your own or someone else's, depending on why you're using the PHP mail function.

$to = "youremailrecipient@example.com";

In the Subject line, type whatever you want to be used as the subject of the emails sent through this PHP script.

$subject = "Your subject here";

The Message line is where the body of the email goes.

$message = "Your message here";

Use the \n parameter to add a new line to the message, so that it isn't all displayed on a single line to the recipient. Add more than one, if you need to.

The "echo" message would be a success or error message to display on the page if the other parameters aren't properly filled out.

echo "The email message was sent.";

More PHP Email Options

Here are a few more options to keep in mind:

  • If you want to include a "From" header line, it's easy to add it to your PHP script.
  • The mail() function included with stock PHP doesn't support SMTP authentication. If you need this function, send the email using SMTP authentication.
  • To make sure users enter an actual email address, validate the text field to make sure it contains an email-like structure.
  • If you want to specify the receiver's name in addition to the "to" address, add the name within the quotes and then put the email address in brackets, such as Person's Name <recipient@example.com>.

Learn more about PHP's send mail function at PHP.net.

Protecting Your Script From Spammers

If you use the mail() function, especially in combination with a web form, make sure you check that it's called from the desired page, and protect the form with something like a CAPTCHA. It's also important to check for suspicious strings, for example, a "Bcc:" followed by a number of email addresses.