What potential pitfalls should be considered when using PHP to send emails?

One potential pitfall when using PHP to send emails is the risk of exposing sensitive information, such as email addresses or passwords, if the code is not properly secured. To mitigate this risk, always sanitize user input and avoid concatenating user-supplied data directly into the email headers.

// Sanitize user input before using it in the email headers
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Set the email headers securely
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

// Send the email using the sanitized input and secure headers
mail('recipient@example.com', $subject, $message, $headers);