How to Send an Email on Error Exceptions in Laravel 9

https://www.itsolutionstuff.com/post/how-to-send-an-email-on-error-exceptions-in-laravel-9example.html

How to Send an Email on Error Exceptions in Laravel 9?

By Hardik Savani May 14, 2022 Category : LaravelPauseUnmuteLoaded: 1.15%Seek to live, currently behind liveLIVERemaining Time -50:07FullscreenHi Dev,

This post is focused on laravel 9 send email on exception. it's simple example of laravel 9 send exception mail. if you have question about how to send mail on exception in laravel 9 then I will give simple example with solution. This article goes in detailed on laravel 9 send email on error. Alright, let’s dive into the steps.

Sometimes we upload code on production and when you have any error on production then we don't know it. Even laravel log on laravel.log file but as a developer, we don't check every day on the log file. so you need something that will inform you when error or exception generate on your application. I will give you the perfect solution for this. When any error or exception generate in your laravel project then it will inform you via email. Yes, We will send an email on Error Exceptions in laravel.

It's totally free. So just follow the below step and add send mail on an error in laravel app.

Step 1: Install Laravel 9

This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Make Configuration

In first step, you have to add send mail configuration with mail driver, mail host, mail port, mail username, mail password so laravel 9 will use those sender configuration for sending email. So you can simply add as like following.

.env

MAIL_MAILER=smtpMAIL_HOST=smtp.gmail.comMAIL_PORT=465MAIL_USERNAME=mygoogle@gmail.comMAIL_PASSWORD=rrnnucvnqlbslMAIL_ENCRYPTION=tlsMAIL_FROM_ADDRESS=mygoogle@gmail.comMAIL_FROM_NAME="${APP_NAME}"

Read Also: Laravel 9 Eloquent Mutators and Accessors Example

Step 3: Create Mail Class

In this step we will create mail class ExceptionOccured for email send on error exception. So let's run bellow command.

php artisan make:mail ExceptionOccured

now, let's update code on ExceptionOccured.php file as bellow:

app/Mail/ExceptionOccured.php

<?php  namespace App\Mail;  use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Mail\Mailable;use Illuminate\Queue\SerializesModels;  class ExceptionOccured extends Mailable{    use Queueable, SerializesModels;      public $content;      /**     * Create a new message instance.     *     * @return void     */    public function __construct($content)    {        $this->content = $content;    }      /**     * Build the message.     *     * @return $this     */    public function build()    {        return $this->view('emails.exception')                    ->with('content', $this->content);    }}

Step 4: Create Blade View

In this step, we will create blade view file for email. In this file we will write all exception details. now we just write some dummy text. create bellow files on "emails" folder.

resources/views/emails/exception.blade.php

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8" />        <meta name="robots" content="noindex,nofollow" />        <style>            body { background-color: #F9F9F9; color: #222; font: 14px/1.4 Helvetica, Arial, sans-serif; margin: 0; padding-bottom: 45px; }            a { cursor: pointer; text-decoration: none; }            a:hover { text-decoration: underline; }            abbr[title] { border-bottom: none; cursor: help; text-decoration: none; }            code, pre { font: 13px/1.5 Consolas, Monaco, Menlo, "Ubuntu Mono", "Liberation Mono", monospace; }            table, tr, th, td { background: #FFF; border-collapse: collapse; vertical-align: top; }            table { background: #FFF; border: 1px solid #E0E0E0; box-shadow: 0px 0px 1px rgba(128, 128, 128, .2); margin: 1em 0; width: 100%; }            table th, table td { border: solid #E0E0E0; border-width: 1px 0; padding: 8px 10px; }            table th { background-color: #E0E0E0; font-weight: bold; text-align: left; }            .hidden-xs-down { display: none; }            .block { display: block; }            .break-long-words { -ms-word-break: break-all; word-break: break-all; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; }            .text-muted { color: #999; }            .container { max-width: 1024px; margin: 0 auto; padding: 0 15px; }            .container::after { content: ""; display: table; clear: both; }            .exception-summary { background: #B0413E; border-bottom: 2px solid rgba(0, 0, 0, 0.1); border-top: 1px solid rgba(0, 0, 0, .3); flex: 0 0 auto; margin-bottom: 30px; }            .exception-message-wrapper { display: flex; align-items: center; min-height: 70px; }            .exception-message { flex-grow: 1; padding: 30px 0; }            .exception-message, .exception-message a { color: #FFF; font-size: 21px; font-weight: 400; margin: 0; }            .exception-message.long { font-size: 18px; }            .exception-message a { border-bottom: 1px solid rgba(255, 255, 255, 0.5); font-size: inherit; text-decoration: none; }            .exception-message a:hover { border-bottom-color: #ffffff; }            .exception-illustration { flex-basis: 111px; flex-shrink: 0; height: 66px; margin-left: 15px; opacity: .7; }            .trace + .trace { margin-top: 30px; }            .trace-head .trace-class { color: #222; font-size: 18px; font-weight: bold; line-height: 1.3; margin: 0; position: relative; }              .trace-message { font-size: 14px; font-weight: normal; margin: .5em 0 0; }              .trace-file-path, .trace-file-path a { color: #222; margin-top: 3px; font-size: 13px; }            .trace-class { color: #B0413E; }            .trace-type { padding: 0 2px; }            .trace-method { color: #B0413E; font-weight: bold; }            .trace-arguments { color: #777; font-weight: normal; padding-left: 2px; }              @media (min-width: 575px) {                .hidden-xs-down { display: initial; }            }</style>    </head>    <body>            <div class="exception-summary">                <div class="container">                    <div class="exception-message-wrapper">                        <h1 class="break-long-words exception-message">{{ $content['message'] ?? '' }}</h1>                        <div class="exception-illustration hidden-xs-down"></div>                    </div>                </div>            </div>              <div class="container">                <div class="trace trace-as-html">                        <table class="trace-details">                            <thead class="trace-head"><tr><th>                                <h3 class="trace-class">                                    <span class="text-muted">(1/1)</span>                                    <span class="exception_title"><span title="ErrorException">ErrorException</span></span>                                </h3>                                <p class="break-long-words trace-message">{{ $content['message'] ?? '' }}</p>                                <p class="">URL: {{ $content['url'] ?? '' }}</p>                                <p class="">IP: {{ $content['ip'] ?? '' }}</p>                            </th></tr></thead>                            <tbody>                                <tr>                                    <td>                                        <span class="block trace-file-path">in <span title="{{ $content['file'] ?? '' }}"><strong>{{ $content['file'] ?? '' }}</strong> line {{ $content['line'] ?? '' }}</span></span>                                    </td>                                </tr>                                @foreach(($content['trace'] ?? []) as $value)                                <tr>                                    <td>                                        at <span class="trace-class"><span title="{{ $value['class'] ?? '' }}">{{ basename($value['class'] ?? '') }}</span></span><span class="trace-type">-></span><span class="trace-method">{{ $value['function'] ?? '' }}</span>(<span class="trace-arguments"></span>)<span class="block trace-file-path">in <span title=""><strong>{{ $value['file'] ?? '' }}</strong> line {{ $value['line'] ?? '' }}</span></span>                                    </td>                                </tr>                                @endforeach                          </tbody>                    </table>                </div>            </div>    </body></html>

Step 5: Send Mail on Exception

Here, every error exception handle on Exceptions/Handler.php file in laravel. in this file we will write code for send email with error message, file, line, trace, url and ip address details. you can get more details and send in email.

You can also store this information on database from here. so let's copy below code and paste on Handler.php file. You need to change recipient email address.

app/Exceptions/Handler.php

<?php  namespace App\Exceptions;  use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;use Throwable;use Log;use Mail;use App\Mail\ExceptionOccured;  class Handler extends ExceptionHandler{    /**     * A list of the exception types that are not reported.     *     * @var array>     */    protected $dontReport = [              ];      /**     * A list of the inputs that are never flashed for validation exceptions.     *     * @var array     */    protected $dontFlash = [        'current_password',        'password',        'password_confirmation',    ];      /**     * Register the exception handling callbacks for the application.     *     * @return void     */    public function register()    {        $this->reportable(function (Throwable $e) {            $this->sendEmail($e);        });    }      /**     * Write code on Method     *     * @return response()     */    public function sendEmail(Throwable $exception)    {       try {               $content['message'] = $exception->getMessage();            $content['file'] = $exception->getFile();            $content['line'] = $exception->getLine();            $content['trace'] = $exception->getTrace();              $content['url'] = request()->url();            $content['body'] = request()->all();            $content['ip'] = request()->ip();               Mail::to('your_email@gmail.com')->send(new ExceptionOccured($content));          } catch (Throwable $exception) {            Log::error($exception);        }    }}

Step 6: Create Routes

In this step, we will add one route that generate exception and you will receive one email notification. We are creating this is a testing route. so let's add it.

routes/web.php

<?php  use Illuminate\Support\Facades\Route;  /*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------|| Here is where you can register web routes for your application. These| routes are loaded by the RouteServiceProvider within a group which| contains the "web" middleware group. Now create something great!|*/    Route::get('/get-error', function () {      $find = App\Models\User::find(100000)->id;      return view('welcome');});

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

Read Also: Laravel 9 Create Multi Language Website Tutorial

http://localhost:8000/get-error

Output: You Email Look Like This

I hope it can help you...

Last updated