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.
I found an answer here
it's just
$message->attachData($StringValue, "Samplefilename.txt");
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With