学习笔记

Study notes

php 忘记密码发邮件,报错:Mailer Error: SMTP connect() failed in php mailer( https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting)

云逐梦54812017-08-27 23:04:00返回列表

用户登陆时忘记密码,常用的找回密码的方式有两种,一种是通过发送短信验证码,另一种是通过发送连接到邮箱,打开连接通过验证后跳转到重置密码界面。

用户登陆时忘记密码,常用的找回密码的方式有两种,一种是通过发送短信验证码,另一种是通过发送连接到邮箱,打开连接通过验证后跳转到重置密码界面。

创建一个修改密码的URL,例如:

$secretkey = "自己定义一个密钥";
$time = time();
$token = md5(用户ID.用户邮箱.$time.$secretkey);
$string = "email=".$email."&time=".$time."&token=".$token;
$sendstr = base64_encode($string);
$url = "http://".自己的域名."/reset_password.php?sendstr = ".$sendstr;
$send_result = sendmail($email,$time,$url);
if($send_result == true){
    return "邮件发送成功";
}else{
    return "邮件发送失败";
}


邮件发送函数:

/**
     * 发送邮件
     */
    public function sendmail($email,$time,$url)
    {
        import("app.lib.PHPMailer.PHPMailerAutoload", null, '.php');
        $mail = new \PHPMailer();

        $mail->isSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = 'test@gmail.com';                 // SMTP username请输入自己的邮箱
        $mail->Password = 'test';                           // SMTP password请输入邮箱密码
        $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
        $mail->Port = 587;                                    // TCP port to connect to
        $mail->CharSet = 'UTF-8';

        $mail->setFrom('test@gmail.com','test');
        $mail->addAddress($email);     // Add a recipient添加收件人邮箱
        $mail->isHTML(true);                                  // Set email format to HTML

        $mail->Subject = "找回密码";
        $mail->Body    = "亲爱的".$email.":<br/>您在".date("Y-m-d H:i:s",$time)."提交了找回密码请求。请点击下面的链接重置密码
(链接24小时内有效)。<br/><a href='".$url."'target='_blank'>".$url."</a>";

        if(!$mail->send()) {
            return false;
        } else {
            return true;
        }

        return false;
    }

在发送过程中总是提示发送失败:

Mailer Error: SMTP connect() failed in php mailer( https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting)

找了半天不知道问题在哪,后来发现原来原因在此:

Google开始为其用户使用新的授权机制,你只要登录您的谷歌帐户,打开下面的地址:

https://www.google.com/settings/security/lesssecureapps

然后点击启用。这样这个错误就会消失啦。


返回
顶部