基于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查看并执行命令了:
邮件服务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文件:
<html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>Bootstrap Template</title> <style> html,body{ width: 100%; height: 100%; } *{ margin: 0; border: 0; } .content{ text-align: center; margin: 50px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-xs-12 col-md-12"> <p class="content">This is a email by Laravel Artisan Command</p> </div> </div> </div> <script> </script> </body></html>
一切准备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,到时见。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.
