您好,欢迎访问一九零五行业门户网

基于Laravel Task-Scheduler定时发送邮件小程序

说明:本文主要学习laravel的artisan command、task scheduler和mail相关知识。做一个简单的小demo,用来定时发邮件。。走完整个流程最多只需一小时。同时,作者会将开发过程中的一些截图和代码黏上去,提高阅读效率。作者的开发环境是本机的mamp集成软件,php7.0,laravel5.2.*。
laravel中artisan command内容可以参看: 服务 —— artisan console ,mail邮件服务内容可以参看: 服务 —— 邮件 ,以及task-scheduler任务定时器可以参看: 服务 —— 任务调度 。
artisan command 新建一个artisan command:
php artisan make:console sendemails --command=emails:send
并在appconsolecommandssendemails.php文件中添加代码:
class sendemails extends command{ /** * the name and signature of the console command. * * @var string */ protected $signature = 'emails:send'; /** * the console command description. * * @var string */ protected $description = 'this is a demo about sending emails to myself'; /** * create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * execute the console command. * * @return mixed */ public function handle() { $this->info('i am handsome'); $this->error('i am not ugly'); }}
写上$description和handle()方法,$description变量用来显示命令的说明,handle()用来处理命令,然后在appconsolecommandskernel.php中注册命令:
protected $commands = [ // commands\inspire::class, commands\sendemails::class, ];
好,这下可以在终端输入php artisan查看并执行命令了:
mail 邮件服务api驱动需要安装guzzlehttp/guzzle这个包,在项目根目录下:
composer require guzzlehttp/guzzle
然后在.env文件中配置下邮件驱动和用户名密码:
然后修改下handle()方法:
/** * execute the console command. * * @return mixed */ public function handle() {// $this->info('i am handsome');// $this->error('i am not ugly'); $user = [ 'email' => 'xxx@xxx.com',//一个有效的邮箱接收地址 'name' => 'liuxiang', ]; $status = mail::send('emails.send', ['user'=>$user], function($msg) use ($user){ $msg->from('xxx@xxx.com', 'liuxiang email');//一个有效的邮箱发送地址 $msg->to($user['email'], $user['name'])->subject('this is a demo about sending emails to myself'); }); if(!$status){ $this->error('fail to send email');exit; } $this->info('success to send email');exit; }
发送的内容在视图emails.send里,新建resources/views/emails/send.blade.php文件:
bootstrap template this is a email by laravel artisan command

一切准备ok,在项目根目录运行邮件发送命令吧,然后会收到邮件发送成功打印:
然后接收的邮箱会收到邮件:
it is working!!!
task-scheduler 每次手动发邮件毕竟不太爽啊,可以利用系统的定时器crontab定时发送,laravel里有任务定时器可以玩一玩。修改app/console/kernel.php文件:
/** * define the application's command schedule. * * @param \illuminate\console\scheduling\schedule $schedule * @return void */ protected function schedule(schedule $schedule) { // $schedule->command('inspire')->hourly(); //$schedule->command('emails:send')->everyfiveminutes(); $schedule->command('emails:send')->everyminutes(); }
在终端输入 crontab -e 添加一个cron条目:
* * * * * php /applications/mamp/htdocs/laravelemail/artisan schedule:run 1>> /dev/null 2>&1
然后程序每隔一分钟发个邮件过来:
总结:本文主要以laravel的artisan command、mail和task-scheduler做一个好玩的小demo,来定时发发骚扰邮件,哈哈。还挺好玩的,可以试一试。。嘛,过几天想结合设计模式来聊聊laravel,到时见。
其它类似信息

推荐信息