How to Send Email From a PHP Script

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

It's relatively easy to send email from a PHP script running on a webpage. You can even specify whether the PHP email script should use a local or remote SMTP server for sending messages.

PHP Mail Script Example

<?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>");
}
?>

In this example, only change the bold text to what makes sense to you. Everything else should be left as is, since what's left are non-editable parts of the script and required in order for the PHP mail function to work correctly.

  • to: 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.
  • subject: Type whatever you want to be used as the subject of the emails sent through this PHP script.
  • body: This is where the body of the email goes. The \n parameter adds a new line to the message so that it isn't all displayed on a single line to the recipient. You can add more than one, as we have above to make multiple lines.
  • echo: The two "echo" messages you see above are just success or error messages to display on the page if the three parameters above are not properly filled out.

More PHP Email Options

If you want the "From" header line to be included in the PHP script, you just need to add that extra header line. That guide will show you how to add an extra option in the script that defines a particular "From" email address, much like a regular email interface.

The mail() function included with stock PHP does not support SMTP authentication. If mail() does not work for you for this or another reason, you can send the email using SMTP authentication. In that guide is also a tutorial on how to make your PHP mail script support SSL encryption.

To make sure users enter an actual email address, you can validate the text field to ensure that it contains an email-like structure.

If you want to specify the receiver's name in addition to the "to" address, just add the name within the quotes and then put the email address in brackets, such as: "Person's Name <recipient@example.com>".

Tip: A lot more information on the send mail function of PHP appears at PHP.net.

Protecting Your Script From Spammer Exploit

If you use the mail() function (in combination with a webform in particular), make sure you check that it's called from the desired page and protect the form with something like a CAPTCHA.

You can also check for suspicious strings (say, "Bcc:" followed by a number of email addresses).