Search code examples
phphtmlswiftmailer

Detect if a PHP exception occurred and output flash message based off that exception


I am using Swiftmailer to send an email and I currently have a try/catch block to see if the Email Addresses are valid based on the Swift_RfcComplianceException. I currently catch the error and output the $e->getMessage() error on the screen. On the form submission for the email I have a variable set up to spit out a success message if the email is sent successfully.

QUESTION: How do I use the same flash message area to output an error message based on whether or not my Swiftmail file has caught an exception. And how do I make this occur on the same page? I am not using AJAX but rather Page Post Back. Right now all I get is a white screen with text, I want the error message to be where the form is submitted from. Thank you.

HTML

<?php if(isset($_SESSION['message'])):?>
            <div id="success-alert" class="alert alert-success text-center">
                <?php
                    echo $_SESSION['message'];
                    unset($_SESSION['message']);
                ?>
            </div>

        <?php elseif(isset($_SESSION['email_error'])) :?>
            <div id="success-alert" class="alert alert-success text-center">
                <?php
                    echo $_SESSION['email_error'];
                    unset($_SESSION['email_error']);
                ?>
            </div>
        <?php endif; ?>

Swiftmailer

try {
    // Create a message
    $message = (new Swift_Message($_POST['subject']))
        ->setFrom('[email protected]')
        ->setTo($finalEmailList) //Array of email address
        ->setBody($_POST['message'], 'text/html')
        ->setReplyTo('[email protected]');
} catch (Swift_RfcComplianceException $e) {
    print($e->getMessage());
}

PHP

if (isset($_POST['submit_email'])) {
        require_once 'views/Swiftmail.php';
        $_SESSION['message']= "Email Sent Successfully";
        $_SESSION['email_error'] = "Invalid Email Address Entered";
}

Solution

  • You just move the error message setting lines from your "main" PHP code ...

    session_start();
    if (isset($_POST['submit_email'])) {
        require_once 'views/Swiftmail.php';
    }
    

    to your Swiftmail.php file ...

    try {
        // Create a message
        $message = (new Swift_Message($_POST['subject']))
            ->setFrom('[email protected]')
            ->setTo($finalEmailList) //Array of email address
            ->setBody($_POST['message'], 'text/html')
            ->setReplyTo('[email protected]');
        $_SESSION['message']= "Email Sent Successfully";
    } catch (Swift_RfcComplianceException $e) {
        $_SESSION['email_error'] = "Invalid Email Address Entered";
    }
    

    FYI, most modern PHP frameworks have flash message components built in.