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.

41 comments:

  1. Best Tutorial for junior laravel developer.
    Thanks.

    ReplyDelete
  2. My code is working is fine but when mail is not delevered to my mail
    my gmail code is here in the .env file

    MAIL_DRIVER=smtp
    MAIL_HOST=smtp.googlemail.com
    MAIL_PORT=465
    MAIL_USERNAME=xxx@gmail.com
    MAIL_PASSWORD=xxxxxx
    MAIL_ENCRYPTION=ssl

    ReplyDelete
  3. u guys are really cool u are making great things to share your knowledge thank you very match for your effort

    ReplyDelete
  4. it gives me error Failed to authenticate on SMTP server with username "mymailid@gmail.com" using 2 possible authenticators.

    ReplyDelete
  5. Why Do you Create Build Method you can not call it any where ??

    ReplyDelete






  6. How to send email with dynamic sender in laravel?

    https://stackoverflow.com/questions/33789327/how-to-send-email-with-dynamic-sender-in-laravel


    help this solution is not working

    ReplyDelete






  7. How to send email with dynamic sender in laravel?

    https://stackoverflow.com/questions/33789327/how-to-send-email-with-dynamic-sender-in-laravel


    help this solution is not working

    ReplyDelete
  8. php artisan make:mail is not working

    ReplyDelete
  9. Hey! How youre doing? I have a 404 | Not found at press the "send" button. Did i miss a pass?

    ReplyDelete
  10. "Connection could not be established with host smtp.mailtrap.io [Connection refused #111]

    ReplyDelete
  11. I get an error.

    BadMethodCallException
    Method App\Http\Controllers\SendEmailController::send does not exist.
    http://localhost:8000/sendemail/send

    ReplyDelete
  12. Thanks it's working good you save my time :)

    ReplyDelete
  13. Class 'App\Mail\SendMail' not found ?

    ReplyDelete
  14. Failed to authenticate on SMTP server with username "lizzardking@gmail.com" using 2 possible authenticators. Authenticator LOGIN returned Expected response code 250 but got an empty response. Authenticator PLAIN returned Expected response code 250 but got an empty response.

    ReplyDelete
  15. Thank your very useful tutorial

    ReplyDelete
  16. when click submit redirect to 404 page.
    plz give solution

    ReplyDelete
  17. It is a very informative tutorial. Thank you.

    ReplyDelete
  18. Very Good Tutorial. But I Have One Question. Email Goes To A Particular Person. I Want To Send Email Not Particular Person. I Want Send Email Every New Person That Enter Her/Him Email Id. Can You Make Tutorial Otherwise Tell Me How I Can Do It. I Need Urgently. Please Do Help Me.

    Thank You
    James

    ReplyDelete
  19. hello sir,
    it doesn't work for me. I got this error when i am trying to send email


    Failed to authenticate on SMTP server with username "xxxxxxx" using 2 possible authenticators.

    ReplyDelete
  20. How to send multiple mail from above same code? I change the name of mail body view name but it doesn't work, help me for same.

    ReplyDelete
  21. Can i send multiple mail with different email body at one time?

    ReplyDelete
  22. Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required
    " i am gettin this error

    ReplyDelete
  23. well code for send email in laravel.

    ReplyDelete
  24. Hi. I got this error "Expected response code 250 but got code "530", with message "530 authentication required" How to fix this ?

    ReplyDelete
  25. Hi. I got this error "Expected response code 250 but got code "530", with message "530 authentication required". Can you tell me how to fix this, please ?

    ReplyDelete
  26. it's not working. showing error
    Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required
    "

    ReplyDelete
  27. Class 'App\Http\Controllers\Mail' not found this error is come any one help me plzz

    ReplyDelete
  28. Awesome Great Lecture, i have no words ,how am i appriciate you ? Great Man

    ReplyDelete
  29. i am stuck on this error plz help me to solve it.
    Connection could not be established with host smtpout.secureserver.net :stream_socket_client(): unable to connect to smtpout.secureserver.net:250 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
    )

    ReplyDelete