What are the common pitfalls when sending emails via SMTP in PHP?

Common pitfalls when sending emails via SMTP in PHP include not properly handling errors, not securing sensitive information like passwords, and not setting the correct headers for the email. To solve these issues, make sure to use try-catch blocks to handle errors, store passwords securely in a separate configuration file, and set headers like Content-Type and From correctly.

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

    // Set SMTP settings
    $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;

    // Set email headers
    $mail->setFrom('your-email@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');
    $mail->Subject = 'Subject of the Email';
    $mail->Body = 'Body of the Email';

    // Send the email
    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'An error occurred: ' . $mail->ErrorInfo;
}