PHP Sending Email

PHP allows you to send emails directly from scripts.

PHP mail() function

The PHP mail() function is used to send emails from scripts.

Syntax

mail(to,subject,message,headers,parameters)
Parameters Description
to Required. Specify the email recipient.
subject Required. Specify the subject of the email. Note: This parameter cannot contain any newline characters.
message Required. Define the message to be sent. Use LF (\n) to separate each line.
headers

Optional. Specify additional headers, such as From, Cc, and Bcc.

Use CRLF (\r\n) to separate additional headers.

parameters Optional. Specify additional parameters for the mail sending program.

Note:PHP requires a mail system that is installed and running to make the mail functions available. The program used is defined by configuration settings in the php.ini file. Please refer to our PHP Mail Reference ManualRead more.

PHP Simple Email

The simplest way to send an email with PHP is to send a text email.

In the following example, we first declare variables ($to, $subject, $message, $from, $headers), and then we use these variables in the mail() function to send an e-mail:

<?php
$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to, $subject, $message, $headers);
echo "Mail Sent.";
?>

PHP Mail Form

With PHP, you can create a feedback form on your own site. The following example sends a text message to a specified e-mail address:

<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
  {
  //send email
  $email = $_REQUEST['email']; 
  $subject = $_REQUEST['subject'];
  $message = $_REQUEST['message'];
  mail("someone@example.com", "Subject: $subject",
  $message, "From: $email" );
  echo "Thank you for using our mail form";
  }
else
//if "email" is not filled out, display the form
  {
  echo "<form method='post' action='mailform.php'>
  Email: <input name='email' type='text' /><br />
  Subject: <input name='subject' type='text' /><br />
  Message:<br />
  <textarea name='message' rows='15' cols='40'>
  </textarea><br />
  <input type='submit' />
  </form>";
  }
?>
</body>
</html>

Example Explanation:

  1. First, check if the email input box has been filled out
  2. If not filled out (such as when the page is first visited), output the HTML form
  3. If filled out (after the form is filled out), send the email from the form
  4. After clicking the submit button, the page is reloaded to display the message that the email has been sent successfully.

PHP Mail Reference Manual

For more information about the PHP mail() function, please visit our PHP Mail Reference Manual.