Saturday, 22 September 2018

Simple Way to Sending an Email in Laravel

If you are beginner level of Laravel framework programmer, then from this post you can learn something new like How can we send an in Laravel. Because any web application sending of email from application is required feature or functionality. So, If you have make any web application in Laravel then you should required to put send an email from your web application. For this here you can find step by step guid how to make simple contact form in Laravel framework and when user submit contact form details then email should be received to owner of website.

Laravel is an robust PHP framework and it has most of all functionality which we would required to make any robust web application. For send an email it has popular SwiftMailer library and by using this library we can get an advantage of different email driver for send an email. Here for send an email we will make one mailable which will handle all email setting. Once this class has been ready then we should define email configuration like host name, port, driver, username and password details under .env file. Below you can find step by step process for best way to sending an email from your Laravel application.




Step 1 - Install Laravel Application


First we have to download Laravel application, for we have to go to command prompt and in this first we should run composer command which handle all dependency of Laravel and after write following command. This command will download Laravel and install into defined folder.


composer create-project laravel/laravel student_crud


Step 2 - Create Controller


Once Laravel framework successfully installed then after we have to first make a controller for handle http request. For this we have to command prompt and write following command. This command will make SendEmailController.php file in app/Http/Controllers.


php artisan make:controller SendEmailController


After create controller in this we have make index() method for load view file in which we will make contact form. This method will load resources/views/send_email.blade.php
file in browser.
app/Http/Controllers/SendEmailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SendEmailController extends Controller
{
    function index()
    {
     return view('send_email');
    }
}


Step 3 - Create View Contact Form


Now we would make view file for display contact form on web page. Below you can find source code of contact form view file.

resouces/views/send_email.blade.php

<!DOCTYPE html>
<html>
 <head>
  <title>How Send an Email in Laravel</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
    border:1px solid #ccc;
   }
   .has-error
   {
    border-color:#cc0000;
    background-color:#ffff99;
   }
  </style>
 </head>
 <body>
  <br />
  <br />
  <br />
  <div class="container box">
   <h3 align="center">How Send an Email in Laravel</h3><br />
   @if (count($errors) > 0)
    <div class="alert alert-danger">
     <button type="button" class="close" data-dismiss="alert">×</button>
     <ul>
      @foreach ($errors->all() as $error)
       <li>{{ $error }}</li>
      @endforeach
     </ul>
    </div>
   @endif
   @if ($message = Session::get('success'))
   <div class="alert alert-success alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>
           <strong>{{ $message }}</strong>
   </div>
   @endif
   <form method="post" action="{{url('sendemail/send')}}">
    {{ csrf_field() }}
    <div class="form-group">
     <label>Enter Your Name</label>
     <input type="text" name="name" class="form-control" value="" />
    </div>
    <div class="form-group">
     <label>Enter Your Email</label>
     <input type="text" name="email" class="form-control" value="" />
    </div>
    <div class="form-group">
     <label>Enter Your Message</label>
     <textarea name="message" class="form-control"></textarea>
    </div>
    <div class="form-group">
     <input type="submit" name="send" class="btn btn-info" value="Send" />
    </div>
   </form>
   
  </div>
 </body>
</html>


Above we can see in Contact form view file we have use jQuery and Bootstrap library for make simple contact form. Laravel use blade template for write server script code between html code. So here we can see validation error message code and success form submission message on web page. Once user has filled all form details then form submission request has been send to send() method of SendEmailController.php controller file which we can see below.


<form method="post" action="{{url('sendemail/send')}}">






Step 4 - Set Route


In this framework we should set the rule of each method which we have created under Controller file. So here we will make two method like index() and send() method under controller. For this we have to go to routes/web.php for set the route.


<?php

Route::get('/sendemail', 'SendEmailController@index');
Route::post('/sendemail/send', 'SendEmailController@send');

?>


Step 5 - Create Mailable Class


Before make mailable class we should define email configuration in .env file of Laravel framework.


MAIL_DRIVER=smtp
MAIL_HOST=smtpout.secureserver.net
MAIL_PORT=80
MAIL_USERNAME=xxxxxxx
MAIL_PASSWORD=xxxxxxx
MAIL_ENCRYPTION=null


Now we are ready for make mailable class for this we have to go teminal and write following command.


php artisan make:mail SendMail


This command will make SendMail.php file inside App\Mail\SendMail.php. In this class we have to define one property with name $data, by using this property we can pass data at the time of create an new instance of this class.

App\Mail\SendMail.php

<?php

namespace App\Mail;

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

class SendMail extends Mailable
{
    use Queueable, SerializesModels;
    public $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->from('john@webslesson.info')->subject('New Customer Equiry')->view('dynamic_email_template')->with('data', $this->data);
    }
}

?>


In above source code we can see build() method, which build the message for send.
from() - This method is use to define from email address.
subject() - This method is use to define subject of an Email
view() - By using this view method we can fetch content from view file which has been put under email body.
with() - This is method is used to pass data into view file, so we can make dynamic email body content.

Step 6 - Make View file for Email Body


In this framework email body content has been get from view file. We below we have make one dynamic_email_template.blade.php view file under resources/views folder.

resources/views/dynamic_email_template.blade.php

<p>Hi, This is {{ $data['name'] }}</p>
<p>I have some query like {{ $data['message'] }}.</p>
<p>It would be appriciative, if you gone through this feedback.</p>


Above we can see in this file we have pass $data variable into this view file. Here we can see how we have pass $data['name'] and $data['message'] variable under this view file. So, this way we can make dynamic email body in Laravel for send email.

Step 7 - Make Send() under Controller


This is last step for send an email in Laravel and in step we have to make send method for handle form submit request for send an email.

app\Http\Controllers\SendEmailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;

class SendEmailController extends Controller
{
    function index()
    {
     return view('send_email');
    }

    function send(Request $request)
    {
     $this->validate($request, [
      'name'     =>  'required',
      'email'  =>  'required|email',
      'message' =>  'required'
     ]);

        $data = array(
            'name'      =>  $request->name,
            'message'   =>   $request->message
        );

     Mail::to('web-tutorial@programmer.net')->send(new SendMail($data));
     return back()->with('success', 'Thanks for contacting us!');

    }
}

?>


Here in this send() method first we have validate form data by using validate() method we can validate form data and if any data not follow validation rules it stop code execution and send validation message to view file.

But suppose all validation rules pass then this method process for send and email. So, here first we have store form data under $data variable. This variable has been pass into dynamic_email_tempate.php view file by using SendMail.php mailable class.

And lastly for send an email we have use Maill class and in this we have use to() in which we can define on which email address email must be received. After this for send an email we have use send() method. In this method we have create new instance of SendMail.php mailable class and in this instance we have pass $data variable value and this method will send an email.

After successfully email send url must be redirect to contact form again form this we have use back() method with success message which has been display above contact form.

Here How can we send an email in Laravel code is ready now we have to run Laravel application, for this we have to go to terminal and write following command.


php artisan serve


If you want to see video tutorial of this post, you can see above the start of post. If you have any query regarding of this tutorial, you can share query under comment box.

0 comments:

Post a Comment