Phpmailer: Error - 200: parsererror on send of mail using phpmailer

Created on 2 Sep 2020  路  1Comment  路  Source: PHPMailer/PHPMailer

I've just started using phpmailer to send mail instead of the basic mail function. I've added the phpmailer function to an ajax script to send a mail on a certain event. All I've added is $mail commands as in the php example script, and modified. The script works perfectly fine on its own, but as soon as I get a "Error - 200: parsererror". it sends the mail, but I get the parsererror.

It looks like a data parsing error relating to json encoding, but I don't think it is. I know this because if you take the previously working code and simply add the $mail commands with no return statements at all, you get this error. And then if you comment out the $mail->send() statement, it works again (but with no mail).

I've posted this on stackoverflow but the replies seem to focus on my method of parsing data in json format, and the fact is that I was parsing data and analysing it in the calling script with no problems and still can if I comment out the $mail->send(); command.
For this reason, I've removed any return statements from my php code as they are not really relevant and only obscure matters in investigating this issue. I can work out with no problems how to return data and parse it once this basic issue with phpmailer is resolved.

So my analysis suggests that it's a bug, but I'm not experienced with phpmailer, so I could be mistaken.

The script is as follows:

    jQuery('#save-supplier').click(function(e){
        e.preventDefault();

        $('#save-supplier').html('<i class="fa fa-cloud"></i> Saving...');

        var formData = new FormData($('#edit-supplier-form')[0]);

        $.ajax({
            type: "POST",
            url: "./ajax/ajaxEditSupplier.php",
            data: formData,
            contentType: false,
            processData:false,
            cache: false,
            dataType: 'json',
            success: function(data) {

                if(data.code =='404'){
                    if(data.msg.first_name!=''){
                        $("#first_name-err").html(data.msg.first_name);
                        $('#save-supplier').html('<i class="fa fa-save mr-5"></i> Save Changes');
                    }
                }else{
                    if (data.err=='invalid') {
                        $("#edit-supplier-form-err-msg").html('Invalid supplier avatar photo extension. Please try again.');
                        $('#save-supplier').html('<i class="fa fa-save mr-5"></i> Save Changes');

                    } else {                
                        $(location).attr("href", "supplier.php?supplier_code=<?php echo $supplier_code; ?>");
                    }
                }
            },
            error: function(data){

                var errorMessage = data.status + ': ' + data.statusText;
                alert('Error - ' + errorMessage);
                $('#save-supplier').html('<i class="fa fa-save mr-5"></i> Save Changes');
            }
        });

        return false;
    });

The script with the phpmailer is:

<?php
    ob_start();

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
    if ($_SESSION['email_method'] == 'phpmailer') {
        require '/var/www/vhosts/mydomain.com/vendor/autoload.php';
    }

    //validation-area
    $err_msg = array();
    $errorMSG = array();

    if (empty($_POST['first-name'])) {
        $errorMSG['first_name'] = "Enter the First name.";
    }

    if(empty($errorMSG)){
        $err_msg['code']=200;
        $err_msg['msg']=$errorMSG;
    }else{
        $err_msg['code']=404;
        $err_msg['msg']=$errorMSG;
        echo json_encode($err_msg); 
        exit();
    }

    //validation ends here

    try {
        // Instantiation and passing `true` enables exceptions
        $mail = new PHPMailer(true);

        //Server settings
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->isSMTP();
        $mail->Host       = 'mydomain.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = '[email protected]';
        $mail->Password   = 'cAp$xxxYY';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        //Recipients
        $mail->setFrom('[email protected]');
        $mail->addAddress('[email protected]');
        $mail->addReplyTo('[email protected]');

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'test email';
        $mail->Body    = 'email body';
        $mail->AltBody = 'email body';

        $mail->send();
    } catch (Exception $e) {
    }

?>

Most helpful comment

It was me answering you on SO, and I'm only going to say the same thing here. If you have a JSON parse error, then the data you're parsing is not valid JSON. It's as simple as that. There's a apt proverb:

When the sage points at the moon, the fool looks at the finger

There are quite a few problems with your code, most of which I already pointed out on SO, but I see you've not changed it before posting here, nor any inspection of the response from your script that might lead to such a parse error.

  • Debug output enabled
  • Only returning data when there is no error
  • No Content-type: application/json header
  • No error checking
  • Starting output buffering but never stopping (likely to result in no response at all)
  • The check for the sending method before loading the autoloader will result in a fatal error if you're not using PHPMailer (because it will attempt to instantiate an unloaded class)

There are logical errors in your JS:

success: function(data) {

                if(data.code =='404'){

If you're retuning a 404, it should be set on the response itself so it can be caught by your error handler, not a 200 success code containing a 404 error. At the very least

Either check the output from your script on the server side, or at the very least inspect what's in data, either in your browser dev tools or stick console.log(data) in the places where you can get at the return value.

There is nothing here that remotely suggests a PHPMailer bug.

>All comments

It was me answering you on SO, and I'm only going to say the same thing here. If you have a JSON parse error, then the data you're parsing is not valid JSON. It's as simple as that. There's a apt proverb:

When the sage points at the moon, the fool looks at the finger

There are quite a few problems with your code, most of which I already pointed out on SO, but I see you've not changed it before posting here, nor any inspection of the response from your script that might lead to such a parse error.

  • Debug output enabled
  • Only returning data when there is no error
  • No Content-type: application/json header
  • No error checking
  • Starting output buffering but never stopping (likely to result in no response at all)
  • The check for the sending method before loading the autoloader will result in a fatal error if you're not using PHPMailer (because it will attempt to instantiate an unloaded class)

There are logical errors in your JS:

success: function(data) {

                if(data.code =='404'){

If you're retuning a 404, it should be set on the response itself so it can be caught by your error handler, not a 200 success code containing a 404 error. At the very least

Either check the output from your script on the server side, or at the very least inspect what's in data, either in your browser dev tools or stick console.log(data) in the places where you can get at the return value.

There is nothing here that remotely suggests a PHPMailer bug.

Was this page helpful?
0 / 5 - 0 ratings