Skip to content
Advertisement

Getting error response while sending email from ionic using PHPMailer

I am trying to create a reset password page in ionic where the user enter his email ,to reset the password of his account on my application. The thing is that I want to send a response from php telling the user if the email was sent to his email or not depending on values sent from php to ionic. The thing that is happening is that the email is sent but it is showing me a response error.

Here is my typescript code:

   async sendEmail() {
        var regEmail = /^([a-zA-Z0-9.-_]+)@([a-zA-Z0-9-]+).([a-z]{2,20})$/;
        if (!regEmail.test(this.resetPasswordForm.value.email)) {
            this.showToast("Invalid email");
            return;
        }

        const loading = await this.load.create({
            message: 'Please wait...'
        });
        loading.present();
        this.auth.sendEmailVerification(this.resetPasswordForm.value).subscribe((data) => {
            console.log(data);
            if (data == "sent") {
                this.showAlert("Great!", "We have sent you an email, check your inbox.");
                this.resetPasswordForm.reset();
            }
            else if (data == "notfound") {
                this.showAlert("Error!", "This email was not found.");
            } else if (data == "error") {
                this.showAlert("Oupss!", "An error occured and email could not be sent.");
            }
        }, (err) => {
                console.log(err);
                this.showAlert("Error!", err.message);
        });
        loading.dismiss();
    }

The php code:

<?php
session_start();
require("headers.php");
require("connection.php");
$userData=file_get_contents("php://input");
$request=json_decode($userData);
$to=$request->email;

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;

// Load Composer's autoloader
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require 'phpmailer/src/Exception.php';

$con=connect();
$checkUser="SELECT count(*) from users where email='$to'";
$res=mysqli_query($con,$checkUser);
$row=mysqli_fetch_array($res);

if($row[0]==1){
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    $randomNumber=mt_rand(100000,999999);
    $_SESSION["random"]=$randomNumber;
    //Server settings
    $mail->SMTPDebug = 2;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp.gmail.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = '';                     // SMTP username
    $mail->Password   = '';                               // SMTP password
    $mail->SMTPSecure = 'tls';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

    //Recipients
    $mail->setFrom('no-reply@gmail.com','charbelalam755@gmail.com');
    $mail->addAddress($to);     // Add a recipient
    print json_encode("sent");

    // Attachments
   // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
   // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = "Password reset email for account: ".$to;
    $mail->Body    = "Your confirmation code to reset your password is: ".$randomNumber;
    //$mail->AltBody =;
    $mail->send();



} catch (Exception $e) {
    print json_encode("error");
}
}else print json_encode("notfound");

mysqli_close($con);
?>

Here is the error that I am getting:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://127.0.0.1/interactive-contact-list/sendEmail.php", ok: false, …}
error:
error: SyntaxError: Unexpected number in JSON at position 6 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:8100/vendor.js:7290:51) at ZoneDelegate.invokeTask (http://localhost:8100/polyfills.js:3505:35) at Object.onInvokeTask (http://localhost:8100/vendor.js:64524:33) at ZoneDelegate.invokeTask (http://localhost:8100/polyfills.js:3504:40) at Zone.runTask (http://localhost:8100/polyfills.js:3273:51) at ZoneTask.invokeTask [as invoke] (http://localhost:8100/polyfills.js:3586:38) at invokeTask (http://localhost:8100/polyfills.js:4727:18) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:8100/polyfills.js:4764:25)
message: "Unexpected number in JSON at position 6"
stack: "SyntaxError: Unexpected number in JSON at position 6↵    at JSON.parse (<anonymous>)↵    at XMLHttpRequest.onLoad (http://localhost:8100/vendor.js:7290:51)↵    at ZoneDelegate.invokeTask (http://localhost:8100/polyfills.js:3505:35)↵    at Object.onInvokeTask (http://localhost:8100/vendor.js:64524:33)↵    at ZoneDelegate.invokeTask (http://localhost:8100/polyfills.js:3504:40)↵    at Zone.runTask (http://localhost:8100/polyfills.js:3273:51)↵    at ZoneTask.invokeTask [as invoke] (http://localhost:8100/polyfills.js:3586:38)↵    at invokeTask (http://localhost:8100/polyfills.js:4727:18)↵    at XMLHttpRequest.globalZoneAwareCallback (http://localhost:8100/polyfills.js:4764:25)"
__proto__: Error
constructor: ƒ SyntaxError()
arguments: (...)
caller: (...)
length: 1
name: "SyntaxError"
prototype: Error {name: "SyntaxError", message: "", constructor: ƒ}
__proto__: ƒ Error()
[[Scopes]]: Scopes[0]
message: ""
name: "SyntaxError"
__proto__:
constructor: ƒ Error()
message: ""
name: "Error"
toString: ƒ toString()
__proto__: Object
text: ""sent"2020-12-27 13:33:10 SERVER -&gt; CLIENT: 220 smtp.gmail.com ESMTP s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:10 CLIENT -&gt; SERVER: EHLO 127.0.0.1<br>↵2020-12-27 13:33:11 SERVER -&gt; CLIENT: 250-smtp.gmail.com at your service, [2a00:6920:f0ef:dc7f:e42f:c0d7:fb12:ac22]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: STARTTLS<br>↵2020-12-27 13:33:11 SERVER -&gt; CLIENT: 220 2.0.0 Ready to start TLS<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: EHLO 127.0.0.1<br>↵2020-12-27 13:33:11 SERVER -&gt; CLIENT: 250-smtp.gmail.com at your service, [2a00:6920:f0ef:dc7f:e42f:c0d7:fb12:ac22]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: AUTH LOGIN<br>↵2020-12-27 13:33:11 SERVER -&gt; CLIENT: 334 VXNlcm5hbWU6<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: [credentials hidden]<br>↵2020-12-27 13:33:11 SERVER -&gt; CLIENT: 334 UGFzc3dvcmQ6<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: [credentials hidden]<br>↵2020-12-27 13:33:11 SERVER -&gt; CLIENT: 235 2.7.0 Accepted<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: MAIL FROM:&lt;no-reply@gmail.com&gt;<br>↵2020-12-27 13:33:11 SERVER -&gt; CLIENT: 250 2.1.0 OK s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: RCPT TO:&lt;charbelalam756@gmail.com&gt;<br>↵2020-12-27 13:33:11 SERVER -&gt; CLIENT: 250 2.1.5 OK s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: DATA<br>↵2020-12-27 13:33:11 SERVER -&gt; CLIENT: 354  Go ahead s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: Date: Sun, 27 Dec 2020 13:33:10 +0000<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: To: charbelalam756@gmail.com<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: From: &quot;charbelalam755@gmail.com&quot; &lt;no-reply@gmail.com&gt;<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: Subject: Password reset email for account: charbelalam756@gmail.com<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: Message-ID: &lt;i0AwjHlt0fMW4cRQ1rpg8Qys7xyFLZyf2MKe365Y@127.0.0.1&gt;<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: X-Mailer: PHPMailer 6.1.7 (https://github.com/PHPMailer/PHPMailer)<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: MIME-Version: 1.0<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: Content-Type: text/html; charset=iso-8859-1<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: <br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: Your confirmation code to reset your password is: 805919<br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: <br>↵2020-12-27 13:33:11 CLIENT -&gt; SERVER: .<br>↵2020-12-27 13:33:12 SERVER -&gt; CLIENT: 250 2.0.0 OK  1609075990 s6sm56953899wro.79 - gsmtp<br>↵2020-12-27 13:33:12 CLIENT -&gt; SERVER: QUIT<br>↵2020-12-27 13:33:12 SERVER -&gt; CLIENT: 221 2.0.0 closing connection s6sm56953899wro.79 - gsmtp<br>↵"
__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ ()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()
headers: HttpHeaders
lazyInit: () => {…}
lazyUpdate: null
normalizedNames: Map(0) {}
__proto__: Object
message: "Http failure during parsing for http://127.0.0.1/interactive-contact-list/sendEmail.php"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://127.0.0.1/interactive-contact-list/sendEmail.php"
__proto__: HttpResponseBase
constructor: class HttpErrorResponse
__proto__: Object

I am using print json_encode(“”) to send response from php to ionic, it’s working everywhere except this one.

Advertisement

Answer

Here’s your problem:

$mail->SMTPDebug = 2;

PHPMailer’s debug output is not JSON compatible, so turn it off:

$mail->SMTPDebug = 0;

You an of course turn it into JSON by injecting your own debug output callback, but I doubt that’s what you want to do.

When debugging things like this, always look at the actual response you’re getting from the server in your browser dev tools – if you had looked at that you would have seen the PHPMailer debug output in the responses.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement