“Phpmailer未能将电子邮件发送到Gmail。”

huangapple go评论71阅读模式
英文:

Phpmailer not sending email to gmail

问题

以下是您的代码的翻译部分:

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

session_start();
if (isset($_SESSION['SESSION_EMAIL'])) {
    header("Location: welcome.php");
    die();
}

// 加载Composer的自动加载器
require 'vendor/autoload.php';

include 'config.php';
$msg = "";

if (isset($_POST['submit'])) {
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = mysqli_real_escape_string($conn, md5($_POST['password']));
    $confirm_password = mysqli_real_escape_string($conn, md5($_POST['confirm-password']));
    $code = mysqli_real_escape_string($conn, md5(rand()));

    if (mysqli_num_rows(mysqli_query($conn, "SELECT * FROM users WHERE email='{$email}'")) > 0) {
        $msg = "<div class='alert alert-danger'>{$email} - 此电子邮件地址已存在。</div>";
    } else {
        if ($password === $confirm_password) {
            $sql = "INSERT INTO users (name, email, password, code) VALUES ('{$name}', '{$email}', '{$password}', '{$code}')";
            $result = mysqli_query($conn, $sql);

            if ($result) {
                echo "<div style='display: none;'>";
                // 创建一个实例;传递`true`启用异常
                $mail = new PHPMailer(true);

                try {
                    // 服务器设置
                    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // 启用详细的调试输出
                    $mail->isSMTP();                                            // 使用SMTP发送
                    $mail->Host       = "tls://smtp.gmail.com";                   // 设置用于发送的SMTP服务器
                    $mail->SMTPAuth   = true;                                   // 启用SMTP身份验证
                    $mail->Username   = 'tk23@gmail.com';                     // SMTP用户名
                    $mail->Password   = '12345678';                               // SMTP密码
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            // 启用隐式TLS加密
                    $mail->Port       = 587;                                    // 连接的TCP端口; 如果已设置`SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`,则使用587

                    // 收件人
                    $mail->setFrom('tk23@gmail.com','Mailer');
                    $mail->addAddress($email);

                    // 内容
                    $mail->isHTML(true);                                  
                    $mail->Subject = '无回复';
                    $mail->Body    = '这是验证链接 <b><a href="http://localhost/login/?verification='.$code.'">http://localhost/login/?verification='.$code.'</a></b>';

                    $mail->send();
                    echo '消息已发送';
                } catch (Exception $e) {
                    echo "无法发送消息。邮件发送程序错误:{$mail->ErrorInfo}";
                }
                echo "</div>";
                $msg = "<div class='alert alert-info'>我们已向您的电子邮件地址发送了验证链接。</div>";
            } else {
                $msg = "<div class='alert alert-danger'>出现了问题。</div>";
            }
        } else {
            $msg = "<div class='alert alert-danger'>密码和确认密码不匹配</div>";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zxx">

<head>
    <title>登录表单 - 勇敢的编码者</title>
    <!-- Meta tag Keywords -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="UTF-8" />
    <meta name="keywords" content="登录表单" />
    <!-- //Meta tag Keywords -->

    <link href="//fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&amp;display=swap" rel="stylesheet">

    <!--/Style-CSS -->
    <link rel="stylesheet" href="css/otp.css" type="text/css" media="all" />
    <!--//Style-CSS -->

    <script src="https://kit.fontawesome.com/af562a2a63.js" crossorigin="anonymous"></script>

</head>

<body>

    <!-- form section start -->
    <section class="w3l-mockup-form">
        <div class="container">
            <!-- /form -->
            <div class="workinghny-form-grid">
                <div class="main-mockup">
                    <div class="alert-close">
                        <span class="fa fa-close"></span>
                    </div>
                    <div class="w3l_form align-self">
                        <div class="left_grid_info">
                            <img src="images/image2.svg" alt="">
                        </div>
                    </div>
                    <div class="content-wthree">
                        <h2>现在注册</h2>
                        <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. </p>
                        <?php echo $msg; ?>
                        <form action="" method="post">
                            <input type="text" class="name" name="name" placeholder="输入您的姓名" value="<?php if (isset($_POST['submit'])) { echo $name; } ?>" required>
                            <input type="email" class="email" name="email" placeholder="输入您的电子邮件" value="<?php if (isset($_POST['submit'])) { echo $email; } ?>" required>
                            <input type="password" class="password" name="password" placeholder="输入您的密码" required>
                            <input type="password" class="confirm-password" name="confirm-password" placeholder="输入您的确认密码" required>
                            <button name="submit" class="btn" type="submit">注册</button>
                        </form>
                        <div class="social-icons">
                            <p>已经有账户! <a href="guest_login.php">登录</a>.</p>
                        </div>
                    </div>
                </div>
            </div>
            <!-- //form -->
        </div>
    </section>
    <!-- //form section start -->

    <script src="js/jquery.min.js"></script>
    <script>
        $(document).ready(function (c) {
            $('.alert-close').on('click', function (c) {
                $('.main-mockup').fadeOut('slow', function (c) {
                    $('.main-mockup').remove();
                });
            });
        });
    </script>

</body>

</html>

请注意,我已经对代码中的 HTML 和 PHP 进行了翻译,但未包括注释。如果您需要更多帮助或有其他问题,请随时提问。

英文:

<sub>I'm making an OTP verification mail for my registration form, and I'm using [tag:phpmailer] to send a verification email to Gmail. but unfortunately, it won't send. I watched a tutorial about making an OTP verification form using phpmailer, still it wont work</sub>

here are my codes for the registration form.

&lt;?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
session_start();
if (isset($_SESSION[&#39;SESSION_EMAIL&#39;])) {
header(&quot;Location: welcome.php&quot;);
die();
}
//Load Composer&#39;s autoloader
require &#39;vendor/autoload.php&#39;;
include &#39;config.php&#39;;
$msg = &quot;&quot;;
if (isset($_POST[&#39;submit&#39;])) {
$name = mysqli_real_escape_string($conn, $_POST[&#39;name&#39;]);
$email = mysqli_real_escape_string($conn, $_POST[&#39;email&#39;]);
$password = mysqli_real_escape_string($conn, md5($_POST[&#39;password&#39;]));
$confirm_password = mysqli_real_escape_string($conn, md5($_POST[&#39;confirm-password&#39;]));
$code = mysqli_real_escape_string($conn, md5(rand()));
if (mysqli_num_rows(mysqli_query($conn, &quot;SELECT * FROM users WHERE email=&#39;{$email}&#39;&quot;)) &gt; 0) {
$msg = &quot;&lt;div class=&#39;alert alert-danger&#39;&gt;{$email} - This email address has been already exists.&lt;/div&gt;&quot;;
} else {
if ($password === $confirm_password) {
$sql = &quot;INSERT INTO users (name, email, password, code) VALUES (&#39;{$name}&#39;, &#39;{$email}&#39;, &#39;{$password}&#39;, &#39;{$code}&#39;)&quot;;
$result = mysqli_query($conn, $sql);
if ($result) {
echo &quot;&lt;div style=&#39;display: none;&#39;&gt;&quot;;
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail-&gt;SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
$mail-&gt;isSMTP();                                            //Send using SMTP
$mail-&gt;Host       = &quot;tls://smtp.gmail.com&quot;;                   //Set the SMTP server to send through
$mail-&gt;SMTPAuth   = true;                                   //Enable SMTP authentication
$mail-&gt;Username   = &#39;tk23@gmail.com&#39;;                     //SMTP username
$mail-&gt;Password   = &#39;12345678&#39;;                               //SMTP password
$mail-&gt;SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
$mail-&gt;Port       = 587;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mail-&gt;setFrom(&#39;tk23@gmail.com&#39;,&#39;Mailer&#39;);
$mail-&gt;addAddress($email);
//Content
$mail-&gt;isHTML(true);                                  
$mail-&gt;Subject = &#39;no reply&#39;;
$mail-&gt;Body    = &#39;Here is the verification link &lt;b&gt;&lt;a href=&quot;http://localhost/login/?verification=&#39;.$code.&#39;&quot;&gt;http://localhost/login/?verification=&#39;.$code.&#39;&lt;/a&gt;&lt;/b&gt;&#39;;
$mail-&gt;send();
echo &#39;Message has been sent&#39;;
} catch (Exception $e) {
echo &quot;Message could not be sent. Mailer Error: {$mail-&gt;ErrorInfo}&quot;;
}
echo &quot;&lt;/div&gt;&quot;;
$msg = &quot;&lt;div class=&#39;alert alert-info&#39;&gt;We&#39;ve send a verification link on your email address.&lt;/div&gt;&quot;;
} else {
$msg = &quot;&lt;div class=&#39;alert alert-danger&#39;&gt;Something wrong went.&lt;/div&gt;&quot;;
}
} else {
$msg = &quot;&lt;div class=&#39;alert alert-danger&#39;&gt;Password and Confirm Password do not match&lt;/div&gt;&quot;;
}
}
}
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;zxx&quot;&gt;
&lt;head&gt;
&lt;title&gt;Login Form - Brave Coder&lt;/title&gt;
&lt;!-- Meta tag Keywords --&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
&lt;meta charset=&quot;UTF-8&quot; /&gt;
&lt;meta name=&quot;keywords&quot;
content=&quot;Login Form&quot; /&gt;
&lt;!-- //Meta tag Keywords --&gt;
&lt;link href=&quot;//fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;
&lt;!--/Style-CSS --&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/otp.css&quot; type=&quot;text/css&quot; media=&quot;all&quot; /&gt;
&lt;!--//Style-CSS --&gt;
&lt;script src=&quot;https://kit.fontawesome.com/af562a2a63.js&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;!-- form section start --&gt;
&lt;section class=&quot;w3l-mockup-form&quot;&gt;
&lt;div class=&quot;container&quot;&gt;
&lt;!-- /form --&gt;
&lt;div class=&quot;workinghny-form-grid&quot;&gt;
&lt;div class=&quot;main-mockup&quot;&gt;
&lt;div class=&quot;alert-close&quot;&gt;
&lt;span class=&quot;fa fa-close&quot;&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;w3l_form align-self&quot;&gt;
&lt;div class=&quot;left_grid_info&quot;&gt;
&lt;img src=&quot;images/image2.svg&quot; alt=&quot;&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;content-wthree&quot;&gt;
&lt;h2&gt;Register Now&lt;/h2&gt;
&lt;p&gt;Lorem ipsum dolor sit amet consectetur adipisicing elit. &lt;/p&gt;
&lt;?php echo $msg; ?&gt;
&lt;form action=&quot;&quot; method=&quot;post&quot;&gt;
&lt;input type=&quot;text&quot; class=&quot;name&quot; name=&quot;name&quot; placeholder=&quot;Enter Your Name&quot; value=&quot;&lt;?php if (isset($_POST[&#39;submit&#39;])) { echo $name; } ?&gt;&quot; required&gt;
&lt;input type=&quot;email&quot; class=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;Enter Your Email&quot; value=&quot;&lt;?php if (isset($_POST[&#39;submit&#39;])) { echo $email; } ?&gt;&quot; required&gt;
&lt;input type=&quot;password&quot; class=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;Enter Your Password&quot; required&gt;
&lt;input type=&quot;password&quot; class=&quot;confirm-password&quot; name=&quot;confirm-password&quot; placeholder=&quot;Enter Your Confirm Password&quot; required&gt;
&lt;button name=&quot;submit&quot; class=&quot;btn&quot; type=&quot;submit&quot;&gt;Register&lt;/button&gt;
&lt;/form&gt;
&lt;div class=&quot;social-icons&quot;&gt;
&lt;p&gt;Have an account! &lt;a href=&quot;guest_login.php&quot;&gt;Login&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;!-- //form --&gt;
&lt;/div&gt;
&lt;/section&gt;
&lt;!-- //form section start --&gt;
&lt;script src=&quot;js/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
$(document).ready(function (c) {
$(&#39;.alert-close&#39;).on(&#39;click&#39;, function (c) {
$(&#39;.main-mockup&#39;).fadeOut(&#39;slow&#39;, function (c) {
$(&#39;.main-mockup&#39;).remove();
});
});
});
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

Somebody told me to replace my port and host to TLS 587, still it wont work. can anybody help me with this problem? thanks.

答案1

得分: 1

这确实有点混乱,如果您按照 PHPMailer 提供的 Gmail 示例 进行操作,您可能会更幸运。PHPMailer 支持Host 属性设置 SMTPSecure 模式和端口号,但更清晰的做法是显式设置这些属性。您遇到问题是因为设置冲突。请改为以下方式:

$mail->Host       = 'smtp.gmail.com';
$mail->SMTPAuth   = true;
$mail->Username   = 'tk23@gmail.com';
$mail->Password   = '12345678';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port       = 465;

故障排除指南解释了各种不同的加密选项,以及它们适用的端口。现在,SMTPS 在端口 465 上是首选选项。

请注意,您仍然可能会遇到问题,因为 Gmail 不再允许简单的基于密码的身份验证;您需要研究 切换到 XOAUTH2

英文:

This is indeed a bit of a mess, and if you had followed the gmail example provided with PHPMailer you'd have had more luck. PHPMailer does support setting the SMTPSecure mode and the port number from the Host property, however, it's much clearer to set those properties explicitly. You're running into a problem with it because you have conflicting settings. Do this instead:

$mail-&gt;Host       = &#39;smtp.gmail.com&#39;;
$mail-&gt;SMTPAuth   = true;
$mail-&gt;Username   = &#39;tk23@gmail.com&#39;;
$mail-&gt;Password   = &#39;12345678&#39;;
$mail-&gt;SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail-&gt;Port       = 465;

The troubleshooting guide explains all about the various different encryption options, and which ports they work on. These days, SMTPS on port 465 is the preferred option.

Note that you are still likely to run into problems because gmail no longer allows simple password-based auth; you need to look into switching to XOAUTH2.

huangapple
  • 本文由 发表于 2023年4月19日 22:41:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定