What are the potential risks of using the "mail()" function in PHP for sending form data?

The potential risks of using the "mail()" function in PHP for sending form data include vulnerability to email injection attacks, potential for spamming, and lack of proper error handling. To mitigate these risks, it is recommended to use a library like PHPMailer or Swift Mailer, which provide better security features and error handling capabilities.

// Example of sending form data using PHPMailer library

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Include PHPMailer autoload file

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

try {
    $mail->isSMTP(); // Set mailer to use SMTP
    $mail->Host = 'smtp.example.com'; // Specify main and backup SMTP servers
    $mail->SMTPAuth = true; // Enable SMTP authentication
    $mail->Username = 'your@example.com'; // SMTP username
    $mail->Password = 'yourpassword'; // SMTP password
    $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465; // TCP port to connect to

    $mail->setFrom('from@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    $mail->isHTML(true); // Set email format to HTML
    $mail->Subject = 'Subject of the email';
    $mail->Body = 'HTML message body';

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