What are the potential pitfalls of using the mail() function in PHP scripts?

The potential pitfalls of using the mail() function in PHP scripts include the risk of emails being marked as spam, lack of error handling, and potential security vulnerabilities if user input is not properly sanitized. To avoid these issues, it is recommended to use a library like PHPMailer which provides better control over email headers, attachments, and has built-in error handling features.

// Example of sending an email using PHPMailer library
require 'vendor/autoload.php';

// Create a new PHPMailer instance
$mail = new PHPMailer\PHPMailer\PHPMailer();

// Set up the SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Set the sender and recipient
$mail->setFrom('from@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');

// Set the email subject and body
$mail->Subject = 'Subject of the email';
$mail->Body = 'Body of the email';

// Send the email
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}