What are the potential security risks associated with using the mail() function in PHP?

The potential security risks associated with using the mail() function in PHP include the possibility of injection attacks if user input is not properly sanitized, the risk of emails being marked as spam due to improper headers, and the potential for unauthorized access if the email server credentials are not securely stored. To mitigate these risks, it is recommended to use a library like PHPMailer or Swift Mailer, which provide more secure ways to send emails in PHP.

// Example using PHPMailer library to send email securely
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // Server settings
    $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;

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

    // Content
    $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}";
}