laravel5.7定时群发邮件

我们可以在服务器上通过 crontab -e 来新增或编辑 Cron 条目,通过 crontab -l 查看已存在的 Cron 条目。

开启调度器

下面是你唯一需要添加到服务器的 Cron 条目,如果你不知道如何添加 Cron 条目到服务器,可以考虑使用诸如 Laravel Forge 这样的服务来为管理 Cron 条目:

* * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

Cron 将会每分钟调用一次 Laravel 命令调度器,当 schedule:run 命令执行后,Laravel 评估你的调度任务并运行到期的任务。

创建:command

 php artisan make:command Mailsend

定时代码

 <?php
    
namespace App\Console\Commands;

use App\Models\Email;
use App\Models\Text;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class Mailsend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sendMail';//command名字

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'send mail';//描述无关紧要

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $url = "XXXXXXXXX";//抓取图片
        $html = file_get_contents($url);
        preg_match_all('/<img[^>]*\/>/',$html,$img);
        //如果出现中文乱码使用下面代码
        //$getcontent = iconv("gb2312", "utf-8",$html);
        $preg = '/http:\/\/.*/';
        preg_match_all($preg,$img[0][0],$oneimg);
        $oneimg =substr($oneimg[0][0],0,-11);//图片
        $text_preg = '/<a .*?>.*?<\/a>/';
        preg_match_all($text_preg,$html,$text);
        $reg3="/>(.*)<\/a>/";
        preg_match_all($reg3,$text[0][2],$title);
        $title = $title[1][0];
        $text=['title'=>$title,'img'=>$oneimg];

        Text::create($text);
        $emails = Email::where('type',1)->select('email','oneday','city_code')->get();//用户列表


        foreach ($emails as $email){
            $watcher = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX;
            $wundu = $this->HttpGet($watcher);
            $wundu = json_decode($wundu, true);
            $day = time()-$email['oneday'];
            $day = ceil($day/86400);
            foreach ($wundu['data']['forecast'] as &$wather ){
                $falg = array_key_exists('aqi',$wather);
                $wather['low']=mb_substr($wather['low'],2,3);
                $wather['high']=mb_substr($wather['high'],2,3);

                if ($falg){
                    $aqi = $wather['aqi'];
                    $wather['quality']=$this->aqi($aqi);
                }
            }

            Mail::send('admin.emails.test', ['tt' => $wundu,'day'=>$day,'img'=>$oneimg,'title'=>$title], function ($message) use ($email) {
                $to =$email['email'];
//                $to = ['396656156@qq.com','997707514@qq.com','528758879@qq.com'];
                $message->to($to)->subject('带你去映雪湖');
            });
            // 返回的一个错误数组,利用此可以判断是否发送成功


        }
//        echo "<textarea style='width:800px;height:600px;'>".$html."</textarea>";

    }

    //空气质量
    public function aqi($aqi)
    {
        if ($aqi < 51) {
            return '优';
        }
        if ($aqi > 50 && $aqi < 101) {
            return '良';
        }
        if ($aqi > 100 && $aqi < 151) {
            return '轻度污染';
        }
        if ($aqi > 150 && $aqi < 201) {
            return '中度污染';
        }
        if ($aqi > 200 && $aqi < 301) {
            return '重度污染';
        }
        if ($aqi>300){
            return '严重污染';
        }
    }

    public function HttpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt ( $curl, CURLOPT_TIMEOUT, 500 );
        // curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36');
        //如果用的协议是https则打开鞋面这个注释         //curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false );
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }


}

配置app/Console/Kernel.php

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Mailsend::class//类名

        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('sendMail')->dailyAt('07:30');//command名
        // $schedule->command('inspire')
        //          ->hourly();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

模板view

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no"/>
    <link href="/css/main.css" type="text/css" rel="stylesheet" />
    <title>测试</title>
</head>
<body>
<div class="content" style="margin: 0 auto;box-shadow: 0 0 10px #333; width: 560px;margin-top: 3.125rem;margin-bottom: 3.125rem; font-size: 1.25rem;color: dimgrey;font-family: '微软雅黑';display: flex;flex-direction: column;text-align: center;">
    <p class="title">今天是我们认识的第 <span style="color: crimson;font-size: 2rem;">{{$day}}</span> 天</p>
    <p class="mind" style="margin-top: 1.5rem;">{{$tt['data']['forecast']['0']['notice']}}</p>
    <p class="wa" style="font-size: 0.875rem;margin-top: 1rem;">最近几天天气</p>
    <p class="wather" style="margin-top: 1rem;font-size: 1rem;">今天  <span></span>{{$tt['data']['forecast']['0']['type']}}  {{$tt['data']['forecast']['0']['low']}}°/{{$tt['data']['forecast']['0']['high']}}°  空气指数:{{$tt['data']['forecast']['0']['aqi']}} {{$tt['data']['forecast']['0']['quality']}}</P>
    <p class="wather" style="margin-top: 1rem;font-size: 1rem;">明天  <span></span>{{$tt['data']['forecast']['1']['type']}}  {{$tt['data']['forecast']['1']['low']}}°/{{$tt['data']['forecast']['1']['high']}}°  空气指数:{{$tt['data']['forecast']['1']['aqi']}} {{$tt['data']['forecast']['1']['quality']}}</P>
    <p class="wather" style="margin-top: 1rem;font-size: 1rem;">后天  <span></span>{{$tt['data']['forecast']['2']['type']}}  {{$tt['data']['forecast']['2']['low']}}°/{{$tt['data']['forecast']['2']['high']}}°  空气指数:{{$tt['data']['forecast']['2']['aqi']}} {{$tt['data']['forecast']['2']['quality']}}</P>
    <p class="one" style="margin-top: 1.25rem; color: cornflowerblue;font-size: 1rem;">{{date('Y/m/d',time())}}</p>
    <div class="img" style="margin-top: 1.25rem;"><img src="{{$img}}" style=" width: 90%;"></div>
    <p class="imgt" style="font-size: 12px;color: darkgray;margin-bottom: 1.25rem;">摄影</p>
    <div class="text" style="font-size: 0.875rem;width: 80%;margin: 0 auto;line-height: 1.5rem;margin-bottom: 3rem;">{{$title}}</div>
</div>
</body>
</html>

php artisan schedule:run 本地调成每分钟执行就能调试
更多定时方法见:任务调度

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 博客之星2020 设计师:CY__ 返回首页