What are the potential pitfalls of using the PHP mail() function for sending emails in a web application?

One potential pitfall of using the PHP mail() function is that it does not provide a way to authenticate the sender, making it easier for malicious users to spoof the sender's email address. To solve this issue, it is recommended to use a library like PHPMailer or Swift Mailer, which provide more features and security options for sending emails.

// Example using PHPMailer library
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', 'Sender Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email body';

    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}