Skip to content
PHP Logo

How important is it to include error handling and validation in PHP scripts that send emails using PHPMailer?

It is crucial to include error handling and validation in PHP scripts that send emails using PHPMailer to ensure that the email is sent successfully and to handle any potential issues that may arise, such as invalid email addresses or server errors. This helps to improve the reliability and robustness of the email sending process.

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

// Initialize PHPMailer
$mail = new PHPMailer(true);

try {
    // Add validation for email address
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Invalid email address');
    }

    // Set up the PHPMailer instance and send the email
    $mail->setFrom('your@example.com', 'Your Name');
    $mail->addAddress($email, 'Recipient Name');
    $mail->Subject = 'Subject';
    $mail->Body = 'Message';

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