繁体   English   中英

使用 PHPMailer 从 ionic 发送 email 时出现错误响应

[英]Getting error response while sending email from ionic using PHPMailer

我正在尝试在 ionic 中创建一个重置密码页面,用户在其中输入他的 email,以在我的应用程序中重置他的帐户密码。 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. 正在发生的事情是 email 已发送,但它向我显示响应错误。

这是我的 typescript 代码:

   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();
    }

php 代码:

<?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 PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// 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);
?>

这是我得到的错误:

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

我正在使用 print json_encode("") 将响应从 php 发送到 ionic,除了这个之外,它在任何地方都可以使用。

这是你的问题:

$mail->SMTPDebug = 2;

PHPMailer的调试output不兼容JSON,所以关闭它:

$mail->SMTPDebug = 0;

您当然可以通过注入您自己的调试 output 回调将其转换为 JSON,但我怀疑这就是您想要做的。

在调试这样的事情时,请始终查看您在浏览器开发工具中从服务器获得的实际响应——如果您查看过,您会在响应中看到 PHPMailer 调试 output。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM