Laravel - Send Email Example

268 0 0 0

Last Updated : 2021-09-16 18:33:13

In order to send an email message from laravel, there are numerous ways to do so. Here is the least complicated one.


  1. Create email
    php artisan make:mail MyTestMail​
    //This will create this file app/Mail/MyTestMail.php


  2. Create .blade view in views/emails folder
    //resources/views/emails/myTestMail.blade.php

    {{-- @component('mail::message') --}}
    <div style="padding: 20px 40px;border: 0px solid red;background-color:#fff;"">
    <br> Hello <b>{{$data['formData']['emailAddress']}},</b> <br><br>
    Your friend, <i><b>'{{$data['formData']['senderName']}}'</b></i> shared this bill event with you.
    <br><br>
    Bill info : <br>

    <span style=''>
    Bill <b>{{$data['formData']['billNumber']}} {{$data['formData']['billTitle']}}</b> <br>
    {{-- Bill Event Id: {{$data['formData']['eventId']}} <br> --}}
    Bill Event : {{$data['formData']['eventName']}} <br>
    Clock <a href="{{$data['formData']['eventFile']}}"> the event file </a> to download <br>
    </span> <br>

    @php
    $billId = $data['formData']['billId'];
    @endphp

    To view this bill please click <a href="@if($data['formData']['billType'] == 'federal'){{ route('bill',['id'=>$billId]) }}@else{{ route('provincialBill',['id'=>$data['bill']->id]) }}@endif">here</a>.

    <br>
    <br>
    Thanks,<br><br>
    {{ config('app.name') }}
    </div>
    {{-- @endcomponent --}}​


  3. Add routing
    Route::get('shareByEmail'  ,['as'=>'shareByEmail' ,'uses'=>'Member@shareByEmail']);​


  4. Send the email message
    public function shareByEmail(Request $request){
    $validator = Validator::make($request->all(), [
    'emailAddress' => 'required|email',
    ]);
    $errors = $validator->errors();

    if(count($errors))
    {//NO Errors
    $responseArray['myResponseMessage'] = view("template.response",['errors'=> $errors ])->render();
    $responseArray['myResponseStatus'] = true ;
    $responseArray['myResponseStatusResult'] = false ;
    }
    else
    {
    $formData = $request->all();
    $loggedInUserId = Auth::user() ;
    $formData['senderEmail'] = $loggedInUserId->email;
    $formData['senderName'] = $loggedInUserId->name;

    $data = [
    'formData' => $formData,
    ];

    \Mail::to($formData['emailAddress'])->send(new \App\Mail\ShareByEmail($data));

    $responseArray['myResponseStatus'] = true ;
    $responseArray['myResponseMessage'] = view("template.response",['successInfo'=>"Your invitation message has been successfully sent"])->render();
    $responseArray['myResponseStatusResult'] = true ;
    }

    if(TheRequest::ajax()){
    return response()->json($responseArray);
    }
    return $responseArray
    }​


  5. In case you needed the ajax call, here it is:
    $('#shareByEmailBTN').on('click', function(){ 
    $("#modalResponseDiv").html('');

    var theForm = $("#shareByEmailForm") ;
    var action = theForm[0].action;
    var method = theForm[0].method;
    var formData = theForm.serialize();

    $.ajax({
    type: "post",
    url: action,
    data:formData,
    beforeSend: function(){
    loader('modalResponseDiv', "afterbegin");
    },
    headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    dataType: "json",
    success: function (msg) {//alert('Success');

    if (msg) {
    if(msg['myResponseStatus'])
    {
    $("#modalResponseDiv").html(msg['myResponseMessage']);

    if(msg['myResponseStatusResult'] === true) {
    setTimeout(()=>{
    $("#shareModal").modal('hide');
    theForm.trigger("reset");
    $("#modalResponseDiv").html('');
    }, 3000);
    }
    }
    else
    {
    //The process has failed on srerver
    alert('Nooo');
    }

    } else {
    alert('There is NO message');
    }
    },

    }).done(function(msg){
    Removeloader();
    }).fail(function () {alert('Failure');
    alert('Failed to load.');
    });

    });​


Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .