Home > Articles > Security > Network Security

PHP: Generating Email from Form Input

  • Print
  • + Share This
One of the easiest things to do in PHP is to generate an email from an HTML form. Chris Cosentino shows you how to do this with a few quick and easy steps.
This article is excerpted from the book Essential PHP for Web Professionals (Prentice Hall PTR, 2001), by Chris Cosentino.
Like this article? We recommend

Like this article? We recommend

One of the easiest things to do in PHP is to generate an email from an HTML form. One of the most common occurrences of this is the ubiquitous feedback form that can be found on most Web sites.


mail( to, subject, body, additional_headers );

The mail() function is a simple way to send email from a script. In fact, the mail() function is probably one of the simplest ways to add more power to your site. If a user registers with your site or provides feedback, you can easily send an email thanking him, and you also can send the user-entered information to any number of administrators for the site.

Usage of the mail function is simple. You need to specify:

  • Who to send the mail to
  • The subject of the mail
  • The body of the message

You can also send additional headers, such as who the mail is from, but it is not required in the function.

The following code is a quick example of how easy it is to generate and send an email from a PHP script.

In the example, we specify a recipient ($to), a subject ($subject) the email message itself ($body), and the sender ($from). Then we package it all up and send it off with the mail() function.

$to = "dino@bedrock.com";
$subject = "Beware of the Goodtimes Virus!";
$body = "Ha! It's a Hoax!\n";
$from = "FROM: Fred Flintstone <fred@bedrock.com>";
mail($to, $subject, $body, $from);
  • + Share This
  • 🔖 Save To Your Account