What are the potential risks of using the PHP mail() function for sending emails, and how can developers mitigate these risks?

One potential risk of using the PHP mail() function is that it can be vulnerable to email injection attacks, where malicious users can inject additional headers into the email to manipulate its content or send spam. To mitigate this risk, developers should sanitize and validate user input before using it in the mail function to prevent any unauthorized headers from being added.

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

// Validate and sanitize user input
$to = filter_var($to, FILTER_SANITIZE_EMAIL);
$subject = filter_var($subject, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);

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