I think you are looking for the attachData() function (https://laravel.com/docs/5.7/mail#attachments). I've done this in the past with pdfs that I generated on the fly and it worked just fine without me having to save the file. I think it should work for uploaded files too.
How to send attachment from request to mail without first saving it to storage?
I have a form that need to send the file attachment to other email. The mailable class has something like attach('file_path') which is not what I want. I want the $request->('file') to be send without first saving it to storage.
Thank.
How do I send the file exactly?
I've try something like this
public function build()
{
$email = $this->from('[email protected]')
->view('emails.contact');
if ($this->input->hasFile('attachments')) {
$files = $this->input->attachments;
foreach ($files as $file) {
$email->attachData($file, $file->getClientOriginalName());
}
}
return $email;
}
I got the file but it's only 66byte and I can't open it. I also try $file->getRealPath() and the result is error 500.
That part I'm not sure on since I've never tried it from an uploaded file before.
Someone on the internet said that PHP can't send file in memory using attachData(). They suggest to save to temp folder. Hmm, that's a lot of work.
Hmm, you might be better off doing that and then deleting the file after the email is sent, but like you said it is a lot of work, and imo not worth it. You could also store them in a temp directory and delete them with a job later, but still that is a lot of extra work that shouldn't be needed.
I feel like this should be possible since I could do it with pdfs, but I'm probably just thinking about it wrong.
I haven't tried this with laravel, but with regular php you can just grab the content of an uploaded file without saving it first by reading the content with file_get_contents().
if (isset($_FILES['fieldName'])) {
$content = file_get_contents($_FILES['fieldName']['tmp_name']);
}
If you can't get file_get_contents() to work with laravels $request object, you might just try using the $_FILES array.
This has worked for me.
$email = $this->from('[email protected]')
->view('emails.contact');
foreach(request()->file() as $file) {
$email->attach($file->getRealPath(), [
'as' => $file->getClientOriginalName(),
'mime' => $file->getMimeType(),
]);
}
You can see it in the documentation https://laravel.com/docs/5.7/mail#attachments .
Please or to participate in this conversation.