LoginSignup
4
1

More than 5 years have passed since last update.

Laravel の Mailable で CSVファイルを添付したメールを送る

Posted at

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

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1