Laravel:5.6:使用命令发送带有文件的电子邮件

时间:2018-10-10 15:12:43

标签: php laravel laravel-5

我正在尝试使用Laravel中的命令发送电子邮件。我想从特定的文件夹发送文件。以前,我是使用带有表单的视图来完成此操作的,但现在我想使用命令来发送电子邮件。该文件将始终位于同一文件夹中。

这是命令代码:

<?php

namespace efsystem\Console\Commands;

use Illuminate\Console\Command;
use Storage;
use Mail;
use Config;

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

     /**
      * The console command description.
      *
      * @var string
      */
     protected $description = 'Sending emails to the users';

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

     /**
      * Execute the console command.
      *
      * @return mixed
      */
     public function handle()
     {
         $data = array(
             'destino' => 'example@gmail.com',
             'asunto' => 'example',
         );

         Mail::send('administracion.email.email_body', $data, function ($message) use ($data) {
             $message->to($data['destino']);
             $message->subject($data['asunto']);
             $message->from(Config::get('mail.username'));
         });

         $this->info('The emails are send successfully!');
     }
 }

2 个答案:

答案 0 :(得分:2)

由于在您使用$request['a_file']的“表单”中,变量是Symfony\Component\HttpFoundation\File\UploadedFile的实例,而扩展名为Symfony\Component\HttpFoundation\File\File

您需要做的是使用您拥有的路径实例化一个File类。

$data = array(
    'destino'    => 'example@gmail.com',
    'asunto'     => 'example',
    'a_file'     => new \Symfony\Component\HttpFoundation\File\File($pathToFile, true)
 );

答案 1 :(得分:1)

您可以使用N69S a_file答案

这是帮助您运行命令的基本技巧。 您的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\SendEmailEfsystem::class,
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->command('emails:send')->everyMonth();
}

/**
 * Register the Closure based commands for the application.
 *
 * @return void
 */
protected function commands()
{
    require base_path('routes/console.php');
}
}

然后如果您要运行它。只需运行php artisan emails:send

或者您想使用可以使用Artisan::call('emails:send);

的代码运行它