Learn 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 web page. You can even specify whether the PHP script should use a local or remote SMTP server for sending messages.

PHP Send Email Example

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

Here's a simple PHP email 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>");
 }
 ?>

More PHP Email Options

There are a few other things you can do with the PHP file.

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, 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.

Want to choose which SMTP server the email uses for authentication? This will alter the header information when the recipient receives the email. You can either use the local SMTP server of the machine that's running the script or specify a remote SMTP server.

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

Tip: There's a lot more information on the send mail function of PHP at PHP.net.

Protecting Your Script From Spammer Exploit

If you use the mail() function (in combination with a web form 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).

Was this page helpful?