6

I think Im close, I just need to pass the $excelFile in Mail but it keeps saying its undefined, yet when I pass $truckstop_post it goes through but that data is not formatted correctly bc it didnt go through the Excel::create yet. How do I get the result of \Excel::create into the Mail::send??

public function truckstopPost()
{   
    $type = 'csv';



    $truckstop_post = Loadlist::select('pick_city', 'pick_state', 'delivery_city', 'delivery_state', 'trailer_type', 'pick_date', 'load_type', 'length', 'width', 'height', 'weight', 'offer_money', 'special_instructions', 'company_contact', 'contact_phone')->where('urgency', 'OPEN')->orderBy('id', 'desc')->get();

    $excelFile = \Excel::create('itransys', function($excel) use ($truckstop_post) {
        $excel->sheet('mySheet', function($sheet) use ($truckstop_post)
        {
            $sheet->fromArray($truckstop_post);

        });


       $info = Load::find(8500);

       $info = ['info'=>$info];


       Mail::send(['html'=>'email.invoice_email_body'], $info, function($message) use ($info, $excelFile){

        $message->to('mike@gmail.com')->subject('subject');

        $message->from('mike@gmail.com', \Auth::user()->name);

        $message->attachData($excelFile, 'Invoice.csv');

        });


        });

    return back()->with('status', 'You Posted Truckstop!');

}

This is what the results look like if I pass $truckstop_post into attachData() but of course thats not a nicely formatted csv file

enter image description here

mcornille
  • 343
  • 2
  • 4
  • 17
  • What exactly is the problem? Generate the excel? Attach it to email? – Dekel Jan 20 '17 at 16:44
  • How to attach it to the email, whats goes in $message->attachData(???, 'Invoice.csv'); Then what happens to ->download($type);? – mcornille Jan 20 '17 at 16:51
  • So remove everything that is not related to the attachment of the file from the question. Say that you have the file X and you would like to attache it. – Dekel Jan 20 '17 at 16:51
  • He doesnt have file X. He's just creating the file on the fly and returning on the route. That's his problem. He's not storing the file – Paras Jan 20 '17 at 16:53
  • @Paras So the question should be "how do I store the data from the route as a file?" This is why I asked what exactly is the problem. – Dekel Jan 20 '17 at 16:57
  • Please post your error message and stack trace – Paras Jan 20 '17 at 18:31
  • ErrorException in MaatwebsiteDemoController.php line 99: Undefined variable: excelFile in MaatwebsiteDemoController.php line 99 at HandleExceptions->handleError('8', 'Undefined variable: excelFile', '/home/vagrant/Code/itransportsystems/app/Http/Controllers/MaatwebsiteDemoController.php', '99', array('excel' => object(LaravelExcelWriter), 'truckstop_post' => object(Collection), 'info' => array('info' => object(Load)))) in MaatwebsiteDemoController.php line 99 at MaatwebsiteDemoController->App\Http\Controllers\{closure}(object(LaravelExcelWriter)) – mcornille Jan 20 '17 at 18:37

3 Answers3

9

You can do it like so

use Maatwebsite\Excel\Excel as BaseExcel;
use Maatwebsite\Excel\Facades\Excel;

...

$filename = "my_file.csv";

$attachment = Excel::raw(
    new PurchaseOrderLinesExport($this->data), 
    BaseExcel::CSV
);
$subject = "Purchase Order"

return $this->from($this->employee->email)
            ->subject("Purchase Order)
            ->view('emails.view')
            ->attachData($attachment, $filename);

Excel::raw() method creates/writes a temporary file and then gets its contents and delete after deleting that file.

Second Solution would be like this if you're using laravel:

public function build()
{
    return $this->markdown('emails.report')
        ->attach(
            Excel::download(
                new AuditReport($this->audit), 
                'report.xlsx'
            )->getFile(), ['as' => 'report.xlsx']
        );
}

Excel::download() returns a BinaryFileResponse that's why it doesn't work directly, but you can grab the file.

ajuchacko91
  • 1,559
  • 1
  • 10
  • 4
  • 2
    Thanks, `Excel::raw(new ExcelExport($this->data), \Maatwebsite\Excel\Excel::XLSX);` combined with `attachData` worked for me. – Tenarius Jan 02 '22 at 16:50
1
public function post()
{   
    $type = 'csv';

    $create_excel = List::select('pick_city', 'pick_state', 'delivery_city', 'delivery_state')->where('urgency', 'OPEN')->orderBy('id', 'desc')->get()->toArray();

    $excelFile = \Excel::create('itrans', function($excel) use ($create_excel) {
        $excel->sheet('mySheet', function($sheet) use ($create_excel)
        {
            $sheet->fromArray($create_excel);


        });

    })->download($type);

    Mail::send(['html'=>'email.email_body'] function($message) {

     $message->to('example@gmail.com')

    ->subject('Email Subject Line');

    $message->from('daniel@twbb.com', 'Daniel');

    $message->attachData($excelFile, 'Invoice.csv');

});

    return $excelFile;

}
Paras
  • 9,258
  • 31
  • 55
0

Starting with Laravel 9, it's possible to use the attachments() method in the Mailable class:

use Illuminate\Mail\Mailables\Attachment;
use Maatwebsite\Excel\Excel as BaseExcel;
use Maatwebsite\Excel\Facades\Excel;

public function attachments(): array
{
    return [
        Attachment::fromData(fn () => Excel::raw(new UsersExport(), BaseExcel::XLSX), 'report.xlsx'),
    ];
}
Sven
  • 1,450
  • 3
  • 33
  • 58