How to set up sending email in Laravel within cron?

Asked

Viewed 417 times

1

After the creation of cron (code below) is made a scan in the database behind changed data. I have to send an email with this data. How can I do that ???

Code of the cron:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class envioEmailBIcron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'envioEmailBI:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command Email';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
       //Pegar os dados no banco
        $sql = ' select * from payments as P, receipts as R ';
        $sql .= ' where P.created_at < CURRENT_DATE AND P.updated_at < CURRENT_DATE ';
        $sql .= ' AND R.created_at < CURRENT_DATE AND R.updated_at < CURRENT_DATE';

        //pega os dados no banco
        $query = \DB::select($sql);

       // executando as funções de envio de e-mail
       $this->info('Example Cron comando rodando com êxito');
    }
}

1 answer

1


To create an email with data coming from the database or any source you feed, do the following:

Type in the command line:

php artisan make:mail ExampleCronSend

this will create an email configuration class with this layout:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class ExampleCronSend extends Mailable
{
    use Queueable, SerializesModels;

    private $dados;

    public function __construct($dados)
    {
        $this->dados = $dados;
    }

    public function build()
    {
        return $this->view('ExampleEmail')
                    ->to('[email protected]')
                    ->with(['dados' => $this->dados]);
    }
}

will now configure a page for the layout of this email, a simple example, create inside the folder resources/views a page named after ExampleEmail.blade.php:

<!doctype html>
<html lang="{{ config('app.locale') }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel - Resultados</title>
    </head>
    <body>    
    @foreach($dados as $r)
        <p>{{$r->description}}</p>
    @endforeach
    </body>
</html>

this provides a nice layout that can still be improved.

Go back to Command and add that call

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use DB;
use App\Mail\ExampleCronSend;

class ExampleCron extends Command
{

    protected $signature = 'example:cron';
    protected $description = 'Example Cron Minutes';
    public function __construct()
    {
        parent::__construct();
    }
    public function handle()
    {

        $dados = DB::table('example')->get();

        Mail::send(new ExampleCronSend($dados));

        $this->info('E-mail enviado com sucesso ...');

    }
}

to test type:

php artisan example:cron

and if the process OK receives the following message:

inserir a descrição da imagem aqui

  • Error showing: [Invalidargumentexception] Please provide a Valid cache path.

  • @alexjosesilva depends on where this is coming from.

  • error already fixed with command: php Artisan view:clear

  • now the error is another: [Errorexception] Undefined Property: stdClass::$Description (View: /var/www/html/api-Finance ira/Resources/views/corpoEmail.blade.php)

  • correct the error in the email body: r->Description does not exist in the database array.

  • I switched to data r->id, r->creat_at

  • New error: [Swift_transportexception] Expected Response code 250 but got code "530", with message "530 5.7.1 Auth entication required "

  • The last error is setting email @alexjosesilva just missing this... try to configure it correctly

  • I asked a question just for this: https://answall.com/questions/249824/erro-laravel-sendemail

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.