What are the best practices for handling email addresses and message bodies in PHP contact forms to ensure proper delivery?

When handling email addresses in PHP contact forms, it is important to validate the email address before sending the message to ensure proper delivery. Additionally, it is good practice to sanitize the message body to prevent any malicious code from being injected. By following these best practices, you can improve the reliability and security of your contact form.

// Validate email address
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $email = $_POST['email'];
} else {
    // Handle invalid email address
    exit('Invalid email address');
}

// Sanitize message body
$message_body = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Send email
$to = 'recipient@example.com';
$subject = 'Contact Form Submission';
$message = "From: $email\n\n$message_body";

mail($to, $subject, $message);