Laravel 5.4 使用 Mail 发送邮件获取验证码功能(使用的配置邮箱为126邮箱)

 1 <?php
 2 
 3 namespace App\Modules\Liveapi\Http\Controllers\Personnel;
 4 
 5 use App\Modules\Liveapi\Http\Controllers\Controller;
 6 use Illuminate\Http\Request;
 7 use Illuminate\Support\Facades\Cache;
 8 use Illuminate\Support\Facades\DB;
 9 use Mail;
10 
11 class UserinfoController extends Controller
12 {
13     
14     public function verify(Request $request)
15     {
16         $email = $request->input("email");
17         if (!$email) {
18             return $this->result([], "邮箱不正确", 401);
19         }
20         if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
21             return $this->result([], "非法邮箱格式", 401);
22         }
23         $model = ShimmerLiveshopSmslog::where('mobile',$email)->orderBy('created_at','desc')->limit(1)->first();
24         $code = json_decode($model->data);
25         $code_end = $code->code;
26         $codetime = floor((time() - strtotime($model->created_at))/60);
27         $time = 5;
28         if($codetime > $time){
29             $code = rand(100000, 999999);
30             
31             $content = '验证码为:'.$code;
32             
33             Mail::raw($content, function ($message)use ($email) {
34                 $message ->to($email)->subject('注册验证码');
35             });
36             
37             $uid = 0;
38             $data = array('uniacid' => Request()->route('uniacid'), 'uid' => $uid, 'type' => 1, 'data' => json_encode(array('code' => $code)), 'mobile' => $email, 'log' => 1);
39 
40             $res = (new ShimmerLiveshopSmslog())->fill($data)->save();
41 
42             return $this->result(['res'=>$res]);
43         }else{
44             return $this->result([], "发送过于频繁,请" . $time . "分钟后再试", 401);
45         }
46     }
47 
48 }
49 
50 ?>

需要注意以下三点:

  1、邮箱配置

  (1)、修改 .env 文件中的邮箱配置为对应的信息,MAIL_HOST根据自己对应的邮箱地址进行修改;MAIL_USERNAME 是你的邮箱账号;注意 MAIL_PASSWORD 不是邮箱的登录密码,是授权码

  

 

   (2)、修改config/mail.php 文件

  

  2、use Mail; 

 

  3、在 Mail::raw 发送邮件时,收件人的邮箱一定要用 use ($email) 传递,不然会报一个收件人邮箱为空的错误

注:1、修改完 .env 文件 一定要使用 php artisan config:cache 清除缓存,不然有可能配置文件不会生效;如果项目已经在服务器上,修改了 .env 文件清除缓存后依然不好用,可以直接在mail.php 中进行配置修改。

  2、发送邮件成功后如果邮箱中没有新邮件提醒,一定要去垃圾邮件中确认一下,有可能会把验证码邮件归类为垃圾邮件。

posted @ 2020-07-21 10:32  糖糖Y  阅读(591)  评论(0编辑  收藏  举报