How can PHP functions be effectively used in the context of sending emails with the mail() function?

When using the mail() function in PHP to send emails, it is important to create a reusable function that encapsulates the email sending logic. This allows for easier maintenance and reusability of the code. By creating a function that accepts parameters such as the recipient email, subject, message, and headers, you can easily customize and send emails throughout your application.

function sendEmail($to, $subject, $message, $headers) {
    if (mail($to, $subject, $message, $headers)) {
        echo "Email sent successfully";
    } else {
        echo "Email sending failed";
    }
}

// Example usage
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email sent using PHP";
$headers = "From: sender@example.com";

sendEmail($to, $subject, $message, $headers);