PHP: mail() function
In the following example, we will demonstrate how to link a form to email submission. It can be useful when you have a contact form and want to receive individual form submissions in your email inbox.
HTML Code
<form method="post" action="./mailer.php">
<input type="hidden" name="send-mail" value="1">
<label for="from_name">Name and Surname</label>
<input name="from_name" id="from_name" type="text" required>
<label for="from">Email Address</label>
<input name="from" id="from" type="email" required>
<label for="message">Your Message</label>
<textarea id="message" name="message"></textarea>
<button type="submit>Send Message</button>
</form>
Our mailer.php
<?php
if ($_REQUEST['send-mail'] ?? 0 == 1) {
$to = "inbox@yourdomain.com";
$subject = "Contact Form";
$message = "Message from the contact form: \n".$_REQUEST['message'];
$headers = array(
'From' => "{$_REQUEST['from_name']} <{$_REQUEST['from']}>",
'Reply-To' => $_REQUEST['from'],
'X-Mailer' => 'PHP/'.phpversion(),
);
mail($to, $subject, $message, $headers);
header('Location: ./thank-you-for-contacting-us');
}
?>
For more information about the mail function, refer to the PHP documentation.