What are the potential consequences of using a poorly written or insecure form mailer script in PHP?

Using a poorly written or insecure form mailer script in PHP can lead to vulnerabilities such as email injection, allowing malicious users to send spam or execute code on the server. To solve this issue, it is important to properly sanitize and validate user input before sending it via email.

// Sanitize and validate user input before sending email
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Send email using a secure method like PHPMailer
require 'PHPMailer/PHPMailer.php';
$mail = new PHPMailer();
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Contact Form Submission';
$mail->Body = "Name: $name\nEmail: $email\nMessage: $message";

if($mail->send()){
    echo 'Message sent successfully';
} else{
    echo 'Message could not be sent.';
}