How to Send Uploaded File as Email Attachment in Laravel

This article solves a simple problem in Laravel – How to send uploaded file as email attachment. In this tutorial we will learn the basics of file upload and sending emails in Laravel.
This article is divided in following 4 steps:

  1. Create the upload form
  2. Process the submitted form
  3. Create email sender class
  4. Create the email template

Step 1: Create the Upload form

In your blade template you can add the below code to create the very basic form for file upload:

<form method="post" action="{{url('upload')}}" enctype="multipart/form-data">
    {{csrf_field()}}
    <div class="row">
        <div class="col-md-4"></div>
        <div class="form-group col-md-4">
            <label for="title">Title:</label>
            <input type="text" class="form-control" name="title">
        </div>
    </div>
    <div class="row">
        <div class="col-md-4"></div>
        <div class="form-group col-md-4">
            <label for="document">Document:</label>
            <input type="file" class="form-control" name="document">
        </div>
    </div>
    </div>
    <div class="row">
        <div class="col-md-4"></div>
        <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Upload</button>
        </div>
    </div>
</form>

Step 2: Process the Submitted Form

In the controller file, we will add code to prcess the data submitted in above form:

<?php
...
...
public function uploadDocument(Request $request) {
    $title = $request->file('title');
    
    // Get the uploades file with name document
    $document = $request->file('document');

    // Required validation
    $request->validate([
        'title' => 'required|max:255',
        'document' => 'required'
    ]);

    // Check if uploaded file size was greater than 
    // maximum allowed file size
    if ($document->getError() == 1) {
        $max_size = $document->getMaxFileSize() / 1024 / 1024;  // Get size in Mb
        $error = 'The document size must be less than ' . $max_size . 'Mb.';
        return redirect()->back()->with('flash_danger', $error);
    }
    
    $data = [
        'document' => $document
    ];
    
    // If upload was successful
    // send the email
    $to_email = test@example.com;
    \Mail::to($to_email)->send(new \App\Mail\Upload($data));
    return redirect()->back()->with('flash_success', 'Your document has been uploaded.');
}

Step 3: Create email sender class

In Laravel you need to create the separate class file to send the email. This class will prepare the email and its body. Also we will attach the uploaded file as inline attachment.
Here is our email class:

<?php
#App\Mail\Upload.php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class Upload extends Mailable
{
    use Queueable, SerializesModels;

    protected $data;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data=[])
    {
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails/upload')
                ->subject('Document Upload')
                ->attach($this->data['document']->getRealPath(),
                [
                    'as' => $this->data['document']->getClientOriginalName(),
                    'mime' => $this->data['document']->getClientMimeType(),
                ]);
    }
}

The important functions used here are:
getRealPath(): Get the temporary upload path
getClientOriginalName(): Get the name of uploaded file
getClientMimeType(): Get the mime type of uploaded file

Step 4: Create the email template

In the above step, our email class refers to the email template as return $this->view('emails/upload'). So we will create the email template at resources/views/emails/upload.blade.php

#resources/views/emails/upload.blade.php

<p>Hi,</p>
<p>Please download the attached file.</p>
<p>Thanks</p>

Now when you submit the form, your uploaded file will be send as email attachment.

Written by Arvind Bhardwaj

Arvind is a Magento and WordPress expert with more than 6 years of industry wide experience.

Website: http://www.webspeaks.in/