PHP 5 mail() Function
PHP allows you to send e-mails directly from a script.
The PHP mail() Function
It is common to send input data from a web form to an email address (typically to the webmaster's email address).
PHP provides a convenient way to send email with the mail() function.
|to||Required. Specifies the recipient's email address(es)|
|subject||Required. Specifies the email's subject line. Note: This parameter cannot contain any newline characters|
|message||Required. Specifies the actual email body (the message to be sent). Each line should be separated with a LF (\n). Lines should not exceed 70 characters|
|headers||Optional. Specifies additional headers such as "From", "Cc", "Bcc", etc. The additional headers should be separated with a CRLF (\r\n)|
|parameters||Optional. Specifies any additional parameters|
|Note: To use the PHP mail() function, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file. Read more in our PHP Mail reference.|
PHP Send Mail Example (NON-SECURE!)
Assume we have the following PHP code on a page:
// display form if user has not clicked submit
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback">
// the user has submitted the form
// Check if the "from" input field is filled out
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
echo "Thank you for sending us feedback";
- If the form has not been submitted; display the HTML feedback form
- When the user clicks on the submit button, check if the "from" input field is filled out
- Get the input data from form
- Send mail with PHP mail() function
|Prevent email injection in PHP!!
In the code above, it is not possible to choose/change the recipient email address as it is hardcoded in the script. You might think this is enough to prevent email injection, but this is wrong!
The code above is not secure, and can be used by spammers to spam others. In the next chapter we will discuss vulnerabilities in e-mail scripts, and how to check user input to make it more secure.
PHP Mail Reference
For more information about the PHP mail() function, visit our PHP Mail Reference.
Thank You For Helping Us!
Your message has been sent to W3Schools.