What best practices should be followed when using PHPMailer to send emails with user input data?
When using PHPMailer to send emails with user input data, it is important to sanitize and validate the user input to prevent any security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to do this is by using PHP's filter_var function to sanitize the user input before using it in the email message.
// Sanitize and validate user input
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Create a new PHPMailer instance
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
// Set up the email message
$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress($email);
$mail->Subject = 'Subject of the email';
$mail->Body = $message;
// Send the email
if ($mail->send()) {
echo 'Email sent successfully';
} else {
echo 'Email could not be sent';
}