What best practices should be followed when sending emails through a contact form in PHP?

When sending emails through a contact form in PHP, it is important to validate user input to prevent injection attacks and ensure data integrity. Additionally, always sanitize user input to prevent cross-site scripting attacks. Use a secure email library to send emails, such as PHPMailer, to prevent email header injection vulnerabilities.

// Example code snippet using PHPMailer to send emails securely

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// Create a new PHPMailer instance
$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    // Recipient
    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email body content';

    // Send the email
    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}