Laravel の Mailable を使って、CSVファイルを添付してメールを送る方法
使うもの
->attachData()
を使う。
コード
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class OrderMail extends Mailable
{
use Queueable, SerializesModels;
public function build()
{
$file = $this->makeFile();
return $this->view('emails.order')
->attachData(stream_get_contents($file), "order.csv");
}
public function makeFile()
{
$header = [
"受注日",
"受注番号",
"商品名",
"単価",
"個数",
"小計",
];
$body = [
"2018/10/17,
"AB1001",
"おいしい林檎ジュース",
100,
12,
1200,
];
$stream = fopen('php://temp', 'w');
fputcsv($stream, $header);
fputcsv($stream, $body);
rewind($stream);
return $stream;
}
}
参考
https://laravel.com/docs/5.7/mail#attachments
https://stackoverflow.com/questions/28313121/laravel-email-attach-text-file-without-actually-creating-the-file