What are common pitfalls when using PHP-Mailer for sending emails?

Common pitfalls when using PHP-Mailer for sending emails include not properly configuring SMTP settings, not handling errors or exceptions, and not sanitizing user input before sending emails. To solve these issues, make sure to set up SMTP settings correctly, implement error handling to catch any issues that may arise during the sending process, and sanitize user input to prevent any malicious code from being executed.

// Example of properly configuring SMTP settings
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Example of implementing error handling
try {
    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Email could not be sent. Error: ' . $mail->ErrorInfo;
}

// Example of sanitizing user input before sending emails
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$body = filter_var($_POST['body'], FILTER_SANITIZE_STRING);

$mail->Subject = $subject;
$mail->Body = $body;