flyingL123
flyingL123

Reputation: 8076

Laravel email attach text file without actually creating the file

Using Laravel, is there a way to attach a file to an email without actually creating the file? Meaning, can I have the email include a text file attachment, but rather than actually saving the file somewhere and telling Laravel the path to the file, can I instead just pass Laravel the data I want to be included in the file?

I think the way to do this is something related to a memory stream but I'm not sure how to actually implement that.

Upvotes: 7

Views: 5799

Answers (2)

zeros-and-ones
zeros-and-ones

Reputation: 4438

I found this question as well, I needed to send csv files as an attachment without writing the file to the public directory where it could be accessed publicly by anyone. This method can be modified to send text files as well:

Send a txt file:

$filename =  'launch_codes.txt';
$file = fopen('php://temp', 'w+');
fwrite($file,"nuclear_arsenal: swordfish");
rewind($file);
Mail::send('emails.launch_codes', [], function($message) use($file, $filename)
        {
            $message->to('[email protected]')
                    ->subject('Confidential Data');
            $message->attachData(stream_get_contents($file), $filename);
        });

fclose($file);

Send a csv file:

        $filename =  'launch_codes.csv';
        $file = fopen('php://temp', 'w+');
        $column_headers = ['Weapon', 'Launch Code'];
        fputcsv($file, $column_headers);
        fputcsv($file, [
           'nuclear_arsenal','swordfish'                        
        ]);

        rewind($file);

        Mail::send('emails.launch_codes', [], function($message) use($file, $filename)
        {
            $message->to('[email protected]')
                    ->subject('Confidential Data');
            $message->attachData(stream_get_contents($file), $filename);
        });

        fclose($file);

Upvotes: 3

Hasan Civelek
Hasan Civelek

Reputation: 166

I found an answer here

it's just

$message->attachData($StringValue, "Samplefilename.txt");

Upvotes: 11

Related Questions