Basic PHP mail() Function code to send emails from a form
Written by Tim SissonYou can use the PHP mail() function to send an email with PHP. The simplest way to do this is to send a text email. This is one way to handle sending you the results when a visitor to your website fills out a form.
Basic PHP email() fuction code
Below is the code for the baic email function. We can take the script and actually use a form on our website to set the variables in the script above to send an email.
<?php
//if "email" variable is filled out, send email
if (isset($_REQUEST['email'])) {
//Email information
$admin_email = "someone@example.com";
$email = $_REQUEST['email'];
$subject = $_REQUEST['subject'];
$comment = $_REQUEST['comment'];
//send email
mail($admin_email, "$subject", $comment, "From:" . $email);
//Email response
echo "Thank you for contacting us!";
}
//if "email" variable is not filled out, display the form
else {
?>
<form method="post">
Email: <input name="email" type="text" /><br />
Subject: <input name="subject" type="text" /><br />
Message:<br />
<textarea name="comment" rows="15" cols="40"></textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
}
?>
So let’s now review what the form is actually doing.
1. The first part checks to make sure the email input field is filled out. If it is not, then it will display the HTML form on the page. If the email is in fact, set (after the visitor fills out the form), it is ready to send.
2. When the submit button is pressed, after the form is filled out, the page reloads and reads that the email input is set, so it sends the email.
Keep in mind, this is a basic tutorial to explain how to use the mail() function in PHP. Using the method, exactly the way it is, can be insecure and should not be used on your website. This tutorial is aiming to provide you the basic of how to use phpmail() and for further use, you may want to look into securing your code to possible hacks.
To learn more about the PHP email function, please see the article on How to create a custom PHP contact form with more information on validation and error checking. If you need further assistance please feel free to ask a question on our support center.
Latest Questions
Need more Help?
Search
Ask the Community!
Current Customers
| Chat: | Click to Chat Now | E-mail: | support@InMotionHosting.com |
|---|---|---|---|
| Call: | 888-321-HOST (4678) | Ticket: | Submit a Support Ticket |

