🚀 DevOps & SRE Certification Program 📅 Starting: 1st of Every Month 🤝 +91 8409492687 🔍 Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Sending Email with attachments in Laravel 5.5 using and PHP & JQuery

Introduction:

Hello Dear Reader,
In this post, I am going to demonstrate detailed steps of how to send email to user’s email id with the files that were submitted by the user as an attachment

The complete working example code has been given in the code section
below
Create all the files and then run command npm run dev in your project directory before testing
Also, the explanation has been provided in the bottom section of the post
Enjoy!

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=<your_mailtrap_username>
MAIL_PASSWORD=<your_mail_trap_password>
MAIL_ENCRYPTION=null
MAIL_FROM=info@test.com
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Notifications\Mails\Users\UserFilesEmail;
use Illuminate\Support\Facades\Mail;
class UserFilesController extends Controller
{
public function submitUserFileAndSendEmail(Request $request) {
$input = $request->all();
$validator = Validator::make($input, [
'username' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'user-files' => 'array|max:3',
'user-files.*' => 'required|file|mimes:jpeg,png,pdf|max:2048'
]);
if ($validator->fails()) {
$data = [
"status"=> "FAILED",
"data"=> [
"message" => $validator->errors(),
"redirect_url" => '#'
]
];
return response()->json($data, 422);
}
try {
if ($this->sendEmailToUser($request)) {
$data = [
"status"=> "OK",
"data"=> [
"status" => "SUCESS"
]
];
return response()->json($data, 200);
} else {
$data = [
"status"=> "FAILED",
];
return response()->json($data, 500);
}
}
}
private function sendEmailToUser(Request $request) {
$input = $request->all();
try {
$emailParams = new \stdClass();
$emailParams->receiverName = $input['username'];
$emailParams->email = $input['email'];
$emailParams->attachments = $input['user-files'];
$emailParams->sender = 'Team Champion';
$emailParams->subject = 'Testing email sending with files';
Mail::to($hospital['email'])->queue(new UserFilesEmail($emailParams));
$response = [
'success' => true,
'message' => 'Email notification will be sent to the given patient shortly!'
];
return response()->json($response, 200);
} catch (\Exception $e) {
$response = [
'success' => false,
'data' => '' ,
'message' => 'There was some problem in sending email'
];
return response()->json($response, 500);
}
}
}
<?php
namespace App\Notifications\Mails\Users;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Config;
class UserFilesEmail extends Mailable
{
use Queueable, SerializesModels;
/**
* The emailParams object instance.
*
* @var emailParams
*/
private $emailParams;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($emailParams) {
$this->emailParams = $emailParams;
}
/**
* Build the message.
*
* @return $this
*/
public function build() {
$emailObj = $this->from(Config::get('app.MAIL_FROM'))
->subject($this->emailParams->subject)
->view('notifications.mails.users.user-files-email')
->text('notifications.mails.hospital.user-files-email-plain')
->with(
[
'emailParams' => $this->emailParams
]);
foreach($this->emailParams->attachments as $index => $userFile) {
$emailObj->attachData(base64_decode($userFile['file']),
$userFile['filename'],
['mime' => $userFile['mime']]
);
}
return $emailObj;
}
}
$('#user_files_form').on('click', function(e) {
e.preventDefault();
submitUserFiles($(this.form));
});
function submitUserFiles(formObj) {
let formData = new FormData($('#user_files_form')[0]);
$.ajax({
type: "POST",
url: formObj.attr('action'),
// Optional line. It's needed if you are using Passport api in your Laravel app
headers: {"Authorization": "Bearer " + localStorage.getItem('p_u_a_b_t')},
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
enctype: 'multipart/form-data',
success: function(response) {
if(response.status === 'OK') {
let data = response.data;
console.log('Response Data: ' + data);
alert ('Done!');
}
},
error: function(errorResponse) {
alert('Responded with some error!');
}
});
}
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
</head>
<body>
<div id="app">
<!-- This is Vue JS application section -->
</div>
<div id=''>
<!-- This is NOT a Vue JS application section -->
<!-- NOTE: The below line enables JQuery in your app. When you check app.js file, it has got require of bootsrap.js
and bootstrap.js imports JQuery from node modules folder -->
<script src="{{ asset('js/app.js') }}"></script>
</div>
</body>
</html>
Hello {{ $emailParams->receiverName }},
New file (s) were submitted by the user Also, it's the Text version.
Please check the attachments for the file/document (s) submitted by the user.
Here's the email id of the submitter: {{$emailParams->patientEmail}}
Thank You,
{{ $emailParams->sender }}
Hello {{ $emailParams->receiverName }},
<p>New file (s) were submitted by the user</p>
<div>
<p>Please check the attachments for the file/document (s) submitted by the user</p>
<p>Here's the email id of the submitter: {{$emailParams->email}}</p>
</div>
Thank You,
<br/>
<i>{{ $emailParams->sender }}</i>
@extends('layouts.app')
@section('content')
<div class="container mt-2">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="card">
<div class="card-header">
User Files Form
</div>
<div class="card-body">
<form class="form-horizontal" method="POST" action="{{ route('submit.user.files') }}" id="user_files_form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" class="form-control" name="username" id="username" value="test-name"/>
<input type="text" class="form-control" name="email" id="email" value="test@gmail.com"/>
<div class="form-group">
<label for="quote_request_file">
Upload file (.pdf, .jpeg, .jpg, .png)
Max three files allowed
</label><br/>
<input type="file" class="" name="user-files[]" id="user_file" accept=".pdf, .jpeg, .jpg, .png" multiple>
</div>
<div class="form-group">
<div class="">
<button type="button" class="btn btn-primary" id="user-files-submit">
Submit Quote
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="{{ asset('js/pages/user-files-script.js') }}"></script>// You may have to change the file path based on the location where you want to keep user-files-script.js
@endsection
Route::post('/submit-user-files', 'UserFilesEmailController@submitUserFileAndSendEmail')->name('submit.user.files');
let mix = require('laravel-mix');
mix.js('resources/assets/js/pages/user-files-script.js', 'public/js/pages');

Explanation:

Step 1:Enable JQuery in your Laravel application
Enable JQuery in your Laravel application by adding below line of code in your blade file or the parent blade file:
<script src="{{ asset('js/app.js') }}"></script>

Refer Laravel-Email-Project\resources\views\layouts\app.blade.php
NOTE: How you make sure, adding above line of code will enable JQuery?
ANS: When you open resources\assets\js\app.js file, you will see it requires ./bootsrap.js file. Now open bootstrap.js file, you will see it has a require statement for importing JQuery. The line in bootstrap.js will look something like shown below:
try {
window.$ = window.jQuery = require('jquery');
//require('bootstrap-sass'); require('bootstrap'); } catch (e) {}

Hence, the above code explains that app.js imports JQuery from the node modules folder and makes it available for all the blade file that uses app.js.

Step 2: Create a form Laravel-Email-Project\resources\views\pages\user-files-form.blade.php, that accepts one file or more than one files from the user. Make sure to have enctype="multipart/form-data" in the form tag

Also, don’t forget to import Laravel-Email-Project\resources\assets\js\pages\user-files-script.js

Step 3: Create a Controller file that accepts the request with files: Laravel-Email-Project\app\Http\Controllers\UserFilesEmailController.php

Step 4: Create a route in web.php

Step 5: Create Laravel-Email-Project\app\Notifications\Mails\Users\UserFilesEmail.php, that will have code to form email and trigger the email with attachments

Step 6: Create Laravel-Email-Project\resources\assets\js\pages\user-files-script.js that will have jquery code to submit the form with files input

Step 7: Create Laravel-Email-Project\resources\views\notifications\mails\users\user-files-email-plain.blade.php that will have text version of the email template

Step 8: Create Laravel-Email-Project\resources\views\notifications\mails\users\user-files-email.blade.php that will have the template of the email body

Step 9: Add the compilation & migration of the user-files-script.js from assets to public directory in Laravel-Email-Project\webpack.mix.js file

Step 10: Open git bash in the project directory and run command: npm run dev

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.