What security considerations should be taken into account when using PHP mail functions?

When using PHP mail functions, it is important to sanitize user input to prevent email header injection attacks. This can be done by validating and filtering user input before using it in the mail function. Additionally, it is recommended to use the fourth parameter of the mail function to specify additional headers like From, Reply-To, and CC to prevent header injection.

$to = 'recipient@example.com';
$subject = 'Test email';
$message = 'This is a test email.';

$from = 'sender@example.com';
$fromName = 'Sender Name';
$replyTo = 'replyto@example.com';
$cc = 'cc@example.com';

$headers = "From: $fromName <$from>" . "\r\n";
$headers .= "Reply-To: $replyTo" . "\r\n";
$headers .= "CC: $cc" . "\r\n";

// 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 email
mail($to, $subject, $message, $headers);