How can the mail() function be integrated into a PHP script to send form data to a specified email address?
To send form data to a specified email address using the mail() function in PHP, you need to set the appropriate headers, such as From, Reply-To, and Content-Type. Additionally, you need to sanitize and validate the form data to prevent security vulnerabilities. Finally, call the mail() function with the recipient email address, subject, message, and headers to send the email.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Sanitize and validate form data
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$body = "Name: $name <br>";
$body .= "Email: $email <br>";
$body .= "Message: $message";
if (mail($to, $subject, $body, $headers)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email. Please try again.";
}
}
?>
Related Questions
- In what scenarios is it appropriate to use JavaScript instead of HTML forms for sending data to the server in a PHP application?
- What are best practices for handling image uploads and generating thumbnails in PHP using the GD library?
- What are the advantages and disadvantages of using a script like EXIFER versus directly enabling the exif module in PHP for reading image metadata?