一: 邮件初始参数配置
配置 .env (demo示例是163邮箱,开启POP3和SMTP服务,获取授权密码)
MAIL_DRIVER=smtp
MAIL_HOST=smtp.163.com
MAIL_PORT=465
MAIL_USERNAME=你的163邮箱地址
MAIL_PASSWORD=你的163邮箱地址对应的授权密码(不是登录密码)
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=你的163邮箱地址
修改 .env 中的 QUEUE_DRIVER 值 (配置文件 config/queue.php 默认是同步'sync
', demo配置'database
'驱动)
QUEUE_DRIVER=database
二: 数据库建表
//队列任务表
php artisan queue:table
//任务执行失败表
php artisan queue:failed-table
//执行数据库迁移
php artisan migrate
三: 生成任务类
php artisan make:job SendEmail
生成之后,在handle方法中处理发送队列邮件
1 <?php 2 3 namespace AppJobs; 4 5 use IlluminateBusQueueable; 6 use IlluminateQueueSerializesModels; 7 use IlluminateQueueInteractsWithQueue; 8 use IlluminateContractsQueueShouldQueue; 9 use IlluminateFoundationBusDispatchable; 10 use IlluminateSupportFacadesMail; 11 12 class SendEmail implements ShouldQueue 13 { 14 use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; 15 16 private $email; 17 18 private $content; 19 20 private $subject; 21 22 /** 23 * Create a new job instance. 24 * 25 * @return void 26 */ 27 public function __construct( $email, $content, $subject) 28 { 29 $this->email = $email; 30 $this->content = $content; 31 $this->subject = $subject; 32 } 33 34 /** 35 * Execute the job. 36 * 37 * @return void 38 */ 39 public function handle() 40 { 41 $email = $this->email; 42 $subject = $this->subject; 43 44 Mail::send( 45 'admin.emails.test', 46 ['content' => $this->content], 47 function ($message) use($email, $subject) { 48 $message->to($email)->subject($subject); 49 } 50 ); 51 52 // Mail::failures() 返回的错误邮件信息,判断是否发送成功. (无错误信息,返回空数组) 53 if(empty(Mail::failures())){ 54 dd('发送成功'); 55 }else{ 56 dd('发送失败'); 57 } 58 } 59 }
四: 对应邮件发送的控制器,任务加到队列中
1 <?php 2 namespace AppHttpControllersAdmin; 3 4 use AppHttpControllersController; 5 use AppJobsSendEmail; 6 7 /** 8 * Description of BookedController 9 */ 10 class BookedController extends Controller { 11 12 public function queueSend() 13 { 14 //邮件发送demo数据 15 $data =[ 16 0=>[ 17 'email'=>'XXXXXX@qq.com', 18 'content'=>'Hello World One', 19 'subject'=>'测试标题一', 20 ], 21 1=>[ 22 'email'=>'XXXXXX@qq.com', 23 'content'=>'Hello World Two', 24 'subject'=>'测试标题二', 25 ] 26 ]; 27 28 foreach ($data as $item){ 29 //数据循环,插入表jobs中,队列初始化数据 30 dispatch(new SendEmail($item['email'],$item['content'],$item['subject'])); 31 } 32 } 33 34 }
五: 执行队列里的任务
//默认只执行一次队列请求,当请求执行完成后就终止
php artisan queue:work
//监听队列请求,只要运行着,就能一直接受请求,除非手动终止
php artisan queue:listen