What are some best practices for creating an email script for a website using PHP?

When creating an email script for a website using PHP, it is important to sanitize user input to prevent SQL injection and cross-site scripting attacks. Additionally, make sure to validate email addresses to ensure they are in the correct format before sending the email. Finally, consider using a library like PHPMailer to handle the email sending process securely.

<?php
// Sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo 'Invalid email address';
    exit;
}

// Use PHPMailer to send email
require 'vendor/autoload.php'; // Include PHPMailer library
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('to@example.com', 'Recipient Name');
$mail->Subject = 'New message from website';
$mail->Body = "Name: $name\nEmail: $email\nMessage: $message";

if ($mail->send()) {
    echo 'Email sent successfully';
} else {
    echo 'Error sending email: ' . $mail->ErrorInfo;
}
?>