项目需要,使用到邮箱注册,考虑发送邮箱验证。核心功能实现如下。
public function sendm(){
$email = $this->request->request("email");
$event = $this->request->request("event");
$event = $event ? $event : 'register';
if (!$email || !\think\Validate::regex($email, '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/')) {
$this->error(__('邮箱不正确'));
}
$last = \app\common\model\Sms::where(['mobile' => $email, 'event' => $event])
->order('id', 'DESC')
->find();
if ($last && time() - $last['createtime'] < 60) {
$this->error(__('发送频繁'));
}
$ipSendTotal = \app\common\model\Sms::where(['mobile' => $email])->whereTime('createtime', '-1 hours')->count();
if ($ipSendTotal >= 5) {
$this->error(__('发送频繁'));
}
if ($event) {
$userinfo = User::getByEmail($email);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changeemail']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
$code = Random::numeric(config('captcha.length')) ;
$time = time();
$ip = request()->ip();
$para=array();
$para["event"]=$event;
$para["mobile"]=$email;
$para["code"]=$code;
$para["ip"]=$ip;
$para["createtime"]=$time;
//$sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $email, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
$sms = new \app\common\model\Sms();
$sms->save($para);
//if($sms->isSuccess()){
//$sms->delete();
//$this->error(__('验证码失败'));
//}
try {
$phpmailer = new PHPMailer();
$phpmailer->CharSet = 'UTF-8';
$phpmailer->IsSMTP();
$phpmailer->Host = 'xxxxx';
$phpmailer->SMTPAuth = true;
$phpmailer->Username = 'xxxxxxxx';
$phpmailer->Password = 'xxxxxx';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->Port = 465;
$phpmailer->isHTML(true);
$phpmailer->From = 'xxxxxx'; // 发件人邮箱地址
$phpmailer->FromName = 'xxx'; // 发件人名称
$phpmailer->Subject = '注册/登录验证码'; // 邮件主题
$phpmailer->AddReplyTo('xxxxxxx', 'xxxxx');
$phpmailer->AddCustomHeader("Content-Type: text/html; charset=UTF-8");
$phpmailer->Body = "xxxxxxxxxx";
$phpmailer->AddAddress($email); // 收件人邮箱地址和名称
if($phpmailer->send()){
$this->success(__('请查看邮箱'));
}else{
$this->error(__('发送失败'. $phpmailer->ErrorInfo));
};
}catch (Exception $e) {
$this->error(__('发送邮箱失败'));
}
}