You 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 the results when a visitor to your website fills out a form.
Below is the code for the basic email function. You can take the script and actually use a form on your 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.
Keep in mind that 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.
If this is your first time setting up php mail() function, we recommend reading the official documentation on using this code as it also includes examples.