What are the potential pitfalls of relying on the mail() function for email delivery in PHP?

The potential pitfalls of relying on the mail() function for email delivery in PHP include lack of error handling, limited configuration options, and potential issues with spam filters. To address these concerns, it is recommended to use a more robust email library like PHPMailer, which provides better error handling, support for SMTP authentication, and other advanced features.

// Example using PHPMailer library for sending emails
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'your_password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;
    
    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    
    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email body content';
    
    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}