如何使用 phpmailer class 发送邮件?

how to send mail with phpmailer class?

我创建了一个 phpMailer class 并将其调用到我的 register.php 文件中,一切正常。 但是找不到如何从 class.

发送电子邮件的方法

这是我的 class:

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}";
        }
    }
}

这是用法:

require "modules/mailer.php";
$email_send = new mailSend();
$email_send->sendMail($email,$message,$subject);

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

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

Notice: Undefined variable: message in D:\Wamp\www\html\modules\register.php on line 115

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>";

您需要先定义变量然后使用它们!

require "modules/mailer.php";
$email_send = new mailSend();

$subject = "Please verify email!";
$message = "Thanks for signing up!<br>
            Please click on the link below:<br><br>
            <a href=".$url.">".$url."</a>";
$email_send->sendMail($email,$message,$subject);

要让 PHPMailer 抛出异常,您需要通过将 true 传递给构造函数来询问它:

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

现在要从您的 class 中获得响应,您需要 return 一些东西,因此将发送函数的结尾更改为:

$result = [];
$mail->send();
    $result['success'] = true;
    $result['message'] = "Mail sent.";
} catch (Exception $e) {
    $result['success'] = false;
    $result['message'] = "Failed. Mailer error: {$mail->ErrorInfo}";
}
return $result;

然后当你调用你的函数时:

$result = $email_send->sendMail($email,$message,$subject);
if ($result['success']) {
    echo $result['message'];
    //Do whatever else you want to do on success
} else {
    echo $result['message'];
}