Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel email attach text file without actually creating the file

Tags:

php

laravel-4

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.

like image 802
flyingL123 Avatar asked Feb 04 '15 03:02

flyingL123


2 Answers

I found an answer here

it's just

$message->attachData($StringValue, "Samplefilename.txt");
like image 119
Hasan Civelek Avatar answered Sep 28 '22 23:09

Hasan Civelek


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);
like image 45
zeros-and-ones Avatar answered Sep 28 '22 23:09

zeros-and-ones