Search code examples
phpajaxemailphpmailer

Send PHP confirmation email admin email is sent


I am using AJAX and PHP to send an email with data from a contact form. I am using the following PHP:

            if (mail($recipient, $subject, $email_content, $email_headers)) {
                // Set a 200 (okay) response code.
                http_response_code(200);
            } else {
                // Set a 500 (internal server error) response code.
                http_response_code(500);
                echo "Oops! Something went wrong and we couldn't send your message.";
            }

This is working fine, but if this first email is sent, I would also like to send a confirmation email with new parameters. I thought I would be able to just set another mail() function after the 200 response code like:

       if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            http_response_code(200);
            mail($email, $confirmation_subject, $confirmation_content, $confirmation_headers);
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

But this is causing neither email to be sent. What is the proper way to implement a confirmation email if the admin email is sent.


Solution

  • When you send headers back the execution basically stops. I've never seen it documented, but I've been bit by this before. Try switching the order of these two:

    http_response_code(200);
    mail($email, $confirmation_subject, $confirmation_content, $confirmation_headers);
    

    to

    mail($email, $confirmation_subject, $confirmation_content, $confirmation_headers);
    http_response_code(200);