How to mail form php
To send a form using PHP, you'll need to use the mail()
function, which is a built-in PHP function that allows you to send an email message. Here's a basic example of how to do it:
HTML Form
<form action="send_email.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea><br><br>
<input type="submit" value="Send">
</form>
PHP Script (send_email.php)
<?php
// Get the form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Set the email headers
$headers = 'From: '. $email. "\r\n".
'Reply-To: '. $email. "\r\n".
'MIME-Version: 1.0'. "\r\n".
'Content-Type: text/plain; charset=UTF-8';
// Set the email body
$body = "Name: $name\n".
"Email: $email\n".
"Message: $message";
// Send the email
mail('[email protected]', 'Subject', $body, $headers);
// Redirect the user to a thank you page
header('Location: thank_you.php');
exit;
?>
In this example, the form is submitted to the send_email.php
script, which retrieves the form data using the $_POST
superglobal. The script then sets the email headers and body, and uses the mail()
function to send the email to the specified recipient.
Note: Make sure to replace [email protected]
with the actual email address you want to send the email to.
Additional Tips:
- Make sure to validate the form data before sending the email to prevent spam and security issues.
- Use a more secure way to send emails, such as using a library like PHPMailer or SwiftMailer, which can help you avoid common email sending pitfalls.
- Consider using a CAPTCHA to prevent spam bots from submitting the form.
- Make sure to test your email sending script thoroughly to ensure it works correctly.