如何使用 phpmailer 类发送邮件?

我创建了一个 phpMailer 类并将其调用到我的 register.php 文件中。但是没有找到如何从课堂发送电子邮件的方法。


这是我的课:


class mailSend {

    public function sendMail($email, $message, $subject)

    {

        require_once('PHPMailer/src/Exception.php');

        require_once('PHPMailer/src/PHPMailer.php');

        require_once('PHPMailer/src/SMTP.php');

        $mail = new PHPMailer\PHPMailer\PHPMailer();

        try {

        $mail->SMTPDebug = 0;

        $mail->isSMTP();

        $mail->Host = "smtp.gmail.com";

        $mail->SMTPAuth = true;

        $mail->Username = "email@gmail.com";

        $mail->Password = "password";

        $mail->Port = 587;

        $mail->setFrom('admin@example.com', 'Mailer');

        $mail->addAddress($email);

        $mail->addReplyTo("user@gmail.com", "Alias");

        $mail->CharSet = "UTF-8";

        $mail->isHTML(true);

        $mail->Subject = $subject;

        $mail->Body = $message;

        $mail->send();

            $success['success'] = "Mail sent.";

        } catch (Exception $e) {

            $errors['mail'] = "Failed. Mailer error: {$mail->ErrorInfo}";

        }

    }

}

这是 usaqe:


require "modules/mailer.php";

$email_send = new mailSend();

$email_send->sendMail($email,$message,$subject);

这是我的问题部分,我正在尝试在注册时向用户发送确认链接但不知道该怎么做,我尝试了几种方法但无法使其工作:


这是我尝试发送并出现错误的方式:


注意:未定义变量:第 115 行 D:\Wamp\www\html\modules\register.php 中的消息


require "modules/mailer.php";

$email_send = new mailSend();

$email_send->sendMail($email,$message,$subject);


$subject = "Please verify email!";

$message = "Thanks for signing up!<br>

            Please click on the link below:<br><br>

            <a href=".$url.">".$url."</a>";


达令说
浏览 105回答 1
1回答

MM们

您需要在使用它们之前定义变量!require "modules/mailer.php";$email_send = new mailSend();$subject = "Please verify email!";$message = "Thanks for signing up!<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Please click on the link below:<br><br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href=".$url.">".$url."</a>";$email_send->sendMail($email,$message,$subject);要让 PHPMailer 抛出异常,您需要通过传递true给构造函数来询问它:$mail = new PHPMailer\PHPMailer\PHPMailer(true);现在要从你的类中得到响应,你需要返回一些东西,所以把你的 send 函数的结尾改成这样:$result = [];$mail->send();&nbsp; &nbsp; $result['success'] = true;&nbsp; &nbsp; $result['message'] = "Mail sent.";} catch (Exception $e) {&nbsp; &nbsp; $result['success'] = false;&nbsp; &nbsp; $result['message'] = "Failed. Mailer error: {$mail->ErrorInfo}";}return $result;然后当你调用你的函数时:$result = $email_send->sendMail($email,$message,$subject);if ($result['success']) {&nbsp; &nbsp; echo $result['message'];&nbsp; &nbsp; //Do whatever else you want to do on success} else {&nbsp; &nbsp; echo $result['message'];}
打开App,查看更多内容
随时随地看视频慕课网APP