What are common security risks associated with sending emails through PHP scripts?

Common security risks associated with sending emails through PHP scripts include injection attacks, where malicious code can be inserted into the email content or headers, and unauthorized access to email server credentials if they are hardcoded in the script. To mitigate these risks, it is recommended to sanitize user input, use secure email server settings, and avoid storing sensitive information in the script.

// Example of sending a secure email using PHPMailer library

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
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_email@example.com';
    $mail->Password = 'your_email_password';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    $mail->setFrom('your_email@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    $mail->Subject = 'Subject of the Email';
    $mail->Body = 'This is the body of the email';

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