What are some best practices for securely sending form data via email in PHP?

Sending form data via email in PHP can pose security risks if the data is not properly sanitized or protected. To securely send form data via email, it is recommended to use PHP's built-in mail function along with proper validation and sanitization of the form input to prevent injection attacks.

<?php

// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Set up email headers
$to = 'recipient@example.com';
$subject = 'Contact Form Submission';
$headers = 'From: ' . $email . "\r\n" .
    'Reply-To: ' . $email . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

// Send email
$mailSent = mail($to, $subject, $message, $headers);

if ($mailSent) {
    echo 'Email sent successfully';
} else {
    echo 'Failed to send email';
}

?>