【问题标题】:Having problem with sending email with PHPMailer?使用 PHPMailer 发送电子邮件时遇到问题?
【发布时间】:2020-11-22 20:27:12
【问题描述】:

当我运行我的 php 程序时,我得到了这个错误:

未定义变量:第 22 行 C:\xampp\htdocs\Trying_login_register\controllers\emailcontroller.php 中的邮件

这是我的 php 代码:

<?php
require 'vendor/autoload.php';
require 'config/constant_email.php';

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

$mail = new PHPMailer(true);
global $mail;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = EMAILaddress; //paste one generated by Mailtrap
$mail->Password = PASSWORD; //paste one generated by Mailtrap
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
function sendVerificationEmail($userEmail, $token)
{
    $body='<h1>Send HTML Email using SMTP in PHP</h1>
    <p>This is a test email I’m sending using SMTP mail server with PHPMailer.</p>';

    $mail->setFrom(EMAILaddress);
    $mail->addReplyTo(EMAILaddress);
    $mail->addAddress('ADDRESS');
    $mail->Subject = 'Verify your email address';
    $mail->isHTML(true);
    $mail->Body = $body;
    if ($mail->send()) {
        echo 'message has been successfully sent';
    }

    else {
        echo 'Mailor error: ' . $mail->ErrorInfo;
    }
}

我找不到问题。请帮帮我。

【问题讨论】:

  • global $mail; 应该被放入函数体中。

标签: php smtp gmail phpmailer


【解决方案1】:

由于三个原因,此代码无法正常工作:

首先,$mail 已在全局范围内定义,因此您不需要在此处使用global $mail - 只需删除该行即可。

接下来,您的sendVerificationEmail 函数确实需要访问$mail 全局,因此您应该在该函数中添加global $mail;内部

最后,它仍然不会做任何事情,因为虽然你已经定义了发送函数,但你并没有调用它,所以它的代码永远不会运行。

另一个小问题是你请求 PHPMailer 在错误时抛出异常(通过将true 传递给构造函数),但是你没有异常处理,所以如果出现错误,你的脚本只会死掉而不是处理错误很好。围绕send 调用的if 语句可以正常工作。

虽然这些东西会修复您编写的内容,但更简单的方法是完全删除函数定义,如下所示:

require 'vendor/autoload.php';
require 'config/constant_email.php';

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

$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = EMAILaddress; //paste one generated by Mailtrap
$mail->Password = PASSWORD; //paste one generated by Mailtrap
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$body='<h1>Send HTML Email using SMTP in PHP</h1>
<p>This is a test email I’m sending using SMTP mail server with PHPMailer.</p>';
$mail->setFrom(EMAILaddress);
$mail->addReplyTo(EMAILaddress);
$mail->addAddress('ADDRESS');
$mail->Subject = 'Verify your email address';
$mail->isHTML(true);
$mail->Body = $body;
if ($mail->send()) {
    echo 'message has been successfully sent';
} else {
    echo 'Mailor error: ' . $mail->ErrorInfo;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 2019-01-18
    • 1970-01-01
    • 2022-08-18
    • 2018-05-16
    • 2013-10-25
    • 1970-01-01
    相关资源
    最近更新 更多