What are the potential pitfalls of using the mail() function in PHP for automated email sending?

One potential pitfall of using the mail() function in PHP for automated email sending is that it can be prone to abuse by spammers if not properly secured. To prevent this, it is important to validate user input, sanitize email content, and implement proper email headers to prevent header injection attacks.

// Example of a secure way to use the mail() function in PHP

$to = 'recipient@example.com';
$subject = 'Subject of the email';
$message = 'This is the message content';

// Sanitize input
$to = filter_var($to, FILTER_SANITIZE_EMAIL);
$subject = filter_var($subject, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);

// Set proper headers to prevent header injection
$headers = "From: yourname@example.com\r\n";
$headers .= "Reply-To: yourname@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

// Send the email
$mailSuccess = mail($to, $subject, $message, $headers);

if ($mailSuccess) {
    echo 'Email sent successfully';
} else {
    echo 'Failed to send email';
}