What is the function of the mail() function in PHP and what are common issues users face when using it?

Issue: Common issues users face when using the mail() function in PHP include emails not being sent, emails being marked as spam, and incorrect email formatting. Solution: To ensure emails are sent successfully and not marked as spam, users should set proper headers, use a reliable SMTP server for sending emails, and validate email addresses before sending.

// Example code snippet with proper headers and using a SMTP server for sending emails
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";

$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\r\n";

ini_set("SMTP", "mail.example.com");
ini_set("smtp_port", "25");

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