使用PHPMailer发送电子邮件有问题吗



当我运行php程序时,我会收到以下错误:

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

这是我的php代码:

<?php
require 'vendor/autoload.php';
require 'config/constant_email.php';
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
$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;
}
}

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

此代码无法工作有三个原因:

首先,$mail已经在全局范围中定义,所以您不需要global $mail,只需删除该行即可。

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

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

另一个小问题是,您已经请求PHPMailer在出现错误时抛出异常(通过将true传递给构造函数(,但您没有异常处理,因此如果出现错误,您的脚本将不会很好地处理错误。您在send调用中使用的if语句会很好。

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

require 'vendor/autoload.php';
require 'config/constant_email.php';
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
$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;
}

相关内容

  • 没有找到相关文章

最新更新