laravel队列发送邮件

使用redis发送邮件,需要下载predis,使用composer 命令

composer require predis/predis

修改.env文件

QUEUE_DRIVER=redis
.....//下面是自己的邮箱配置
MAIL_DRIVER=smtp
MAIL_HOST=smtp.163.com
MAIL_PORT=25
MAIL_USERNAME=***********@163.com(这里填写163邮箱的账号)
MAIL_PASSWORD=********(这里填写163授权码不是密码)
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=***********@163.com(发件人:这里填写163邮箱的账号)
MAIL_FROM_NAME=LX(发件人名字)

创建任务

php artisan make:job SendEmail

SendEmail.php文件内容如下,备注:要引入use App\Mail\VerifyEmail;邮件类

email = $email;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 验证错误就清除缓存
        Cache::store('redis')->forget('code-'.$this->email);
        Mail::to($this->email)->send(new RegisterCode($this->email));
    }
}

生成一个邮件类

php artisan make:Mail VerifyEmail

VerifyEmail.php文件内容如下

email=$email;
        $this->subject='标题';
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $key = 'code-'.$this->email;//编辑键名
        $code = rand(1000,9999);//随机验证码
        $expiredAt = now()->addMinutes(10);//有效时间
        //验证码写入redis缓存
        Cache::store('redis')->put($key, ['email' => $this->email, 'code' => $code], $expiredAt);
        //取出缓存数据用于写入日志
        $codeData = Cache::store('redis')->get('code-' . $this->email);
        \Log::info(['注册'=>$codeData]);//写入日志
        //邮件视图及传入的参数
        return $this->view('emails.email')->with(['code'=>$code,]);
    }
}

编辑邮件视图
在目录文件resources/views/emails/email.blade.php中编写




    
    Soda


Soda

Soda Email Verification

Thanks for getting started with Soda!

Here is the confirmation code for your registration:{{$code}}

All you have to do is copy confirmation code and paste it to your form to complete the registration.


Thanks.

© 2019 Soda. All right reserved.

创建控制器

php artisan make:controller UserController

UserController.php文件内容如下

namespace App\Http\Controllers;


use App\Jobs\SendEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class UserController extends Controller
{
    //
    public function sendEmail(Request $request)
    {
        //先清除以这个邮件名为键名的redis缓存
        Cache::store('redis')->forget('code-' . $request->email);
        try {
            //推送队列
            SendEmail::dispatch($request->email);
        } catch (\Exception $exception) {
            return  response() -> json('发送失败');
        }
        return  response() -> json('发送成功');
    }
}
//接收到验证码以后可从redis缓存中取出对比是否正确,下为取出方式
Cache::store('redis')->get('code-' . $request->email);

生成路由

Route::group(['namespace' => 'Api'], function () {
    Route::post('email', 'UserController@sendEmail');//发送邮件验证
})

启动队列

# 运行队列监听
php artisan queue:work --daemon

你可能感兴趣的:(laravel队列发送邮件)