What is the purpose of the mail() function in PHP and how does it work?

The mail() function in PHP is used to send emails from a web server. It takes parameters such as the recipient's email address, subject, message, and additional headers. The function then sends the email using the server's configured mail transfer agent.

$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@example.com";

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

if($mail_sent) {
    echo "Email sent successfully.";
} else {
    echo "Email sending failed.";
}