Receiving emails from contact form in laravel 8 using Mailgun

Receive emails from your contact form using laravel 8 Mailable with Mailgun

Posted by Margie Crona on May 17, 2021

This tutorial will show you a basic example of how you can receive emails from your contact form on your Laravel 8 web platform.

Assuming you have set up your email hosting service such as Zoho or Basecamp.

step 1 Create your Mailgun account.

Go here https://www.mailgun.com/ and create an account. You can use the email you creating from the email hosting service i.e. admin@yourcompanyname.com.

Step 2. Copy details from your Mailgun account to .env file in Laravel

Once you login in to you Mailgun account click on the "sending" dropdown tab on the side menu. Then you will see the "overview" tab click on that. You will see two options "API" and "SMTP", click on smtp. You will see some details pop up at the bottom.

Copy username and default password to MAIL_USERNAME and MAIL_PASSWORD of your .env file. Also put your email address in MAIL_FROM_ADDRESS.

MAIL_MAILER=smtp MAIL_DRIVER=mailgun

MAIL_HOST=smtp.mailgun.org MAIL_PORT=587

MAIL_USERNAME=mailgunusername MAIL_PASSWORD=mailgundefaultpassword MAIL_ENCRYPTION=tls

MAIL_FROM_ADDRESS=youremailaddress MAIL_FROM_NAME="${APP_NAME}"

Step 3. Create mail class ContactMail by execute command

php artisan make:mail ContactMail

This is what it looks like in "app/Mail/ContactMail.php" after setting request data that will be passed from the mail form.

<?php

namespace App\Mail;

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

class ContactMail extends Mailable
{
    use Queueable, SerializesModels;

    public $firstname;
    public $lastname;
    public $phone;
    public $email;
    public $messageLines;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($validatedData)
    {
        $this->firstname = $validatedData['firstname'];
        $this->lastname =  $validatedData['lastname'];
        $this->phone = $validatedData['phone'];
        $this->email = $validatedData['email'];
        $this->messageLines = explode("\n", $validatedData['message']);
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from($this->email)->view('mail-template');
    }
}

Step 4. Execute command make to make controller.

php artisan make:controller ContactMailController

This is what it looks like in "app/Http/Controllers/ContactMailController.php" after setting request data that will be passed from the mail form.

namespace App\Http\Controllers;

use App\Http\Requests\ContactRequest;

use App\Mail\ContactMail;

use Illuminate\Http\RedirectResponse;

use Illuminate\Support\Facades\Mail;

class ContactMailController extends Controller {

public function index() {

      return view('contact');

}

/** * Send Contact Email Function via Mail. * * @return RedirectResponse */

public function contactSendMail(ContactRequest $request): RedirectResponse {

         $validatedData = $request->validated();

         Mail::to("youremailaddress")->send(new ContactMail($validatedData));

         return back();

}

}

Step. 5 Create request in order to validate data from mail form

php artisan make:request ContactRequest

app/Http/Requests/ContactRequest.php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ContactRequest extends FormRequest {

/** * Determine if the user is authorized to make this request. * * @return bool */

public function authorize() {

        return true;

}

/** * Get the validation rules that apply to the request. * * @return array */

public function rules() {

       return [

            'firstname' => 'required|max:255|string',

             'lastname' => 'max:255|string',

             'email' => 'required|max:255|email',

             'phone' => 'numeric|nullable',

             'message' => 'required|max:200|string',

         ];

    }

}

Step. 6 add route in web.php

Go to "/routes/web.php" and add routes

use App\Http\Controllers\ContactMailController;
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::middleware(['guest'])->group(function(){

Route::get('/', [ContactMailController::class, 'index'])->name('contact');

Route::post('/contact', [ContactMailController::class, 'contactSendMail'])->name('contact.send');

});

Step 7. create view for mail template

Go to view folder and create markup for mail template 

This is in "/resources/view/mail-template" see below example.

<ul>
    @if($firstname)
        <li>
             <strong>{{ $firstname }}strong>
        --li>
    @endif
    @if($lastname)
        <li>
             <strong>{{ $lastname }}strong>
        --li>
    @endif
    @if($phone)
        <li>
            <strong>{{ $phone }}strong>
        --li>
    @endif
    @if($email)
        <li>
            <strong>{{ $email }}strong>
        --li>
    @endif

<hr>
@if($messageLines)
    <h4>
        Message:
    h4>
    <p>
        @foreach ($messageLines as $messageLine)
            {{ $messageLine }}<br>
        @endforeach
    --p>
    <hr>
@endif

Step 8. create view for mail form

Go to view folder and create markup for mail form 

This is in "/resources/view" see below example.

<!DOCTYPE html>
<head>
    <meta charset="utf-8">

    <title>Wikicode receiving mail tutorial</title>

    <meta name="description" content="Wikicode receiving mails from contact form using mailable in Laravel 8">
    <meta name="author" content="Wikicodes">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<html>
<body>
<div class="container mt-4">
    <div>Contact Form</div>
    <form method="post" action="{{ route('contact.send') }}">
        <div class="form-group">
            <label for="exampleInputFirstname">Firstname</label>
            <input type="text" class="form-control" id="exampleInputFirstname" name="firstname" aria-describedby="Firstname" placeholder="First name" required>
        </div>
        <div class="form-group">
            <label for="exampleInputLastname">Lastname</label>
            <input type="text" class="form-control" id="exampleInputLastname" name="lastname" aria-describedby="Lastname" placeholder="Last name" required>
        </div>
        <div class="form-group">
            <label for="exampleInputEmail">Email</label>
            <input type="email" class="form-control" id="exampleInputEmail" name="email" placeholder="Email" required>
        </div>
        <div class="form-group">
            <label for="exampleInputPhone">Phone number</label>
            <input type="text" class="form-control" id="exampleInputPhone" name="phone" placeholder="Phone number" required>
        </div>
        <div class="form-group">
            <label for="exampleInputMessage">Message</label>
            <textarea class="form-control" id="exampleInputMessage" name="message" placeholder="Please enter enter your message" required></textarea>
        </div>
        <input name="_token" value="{{ csrf_token() }}" type="hidden">
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</div>
</body>
</html>

Step 9. Start server

php artisan serve

Once everything is in place fill in the form and click submit. Now check your email hosting service to see if the email was receive

 If you wish to download this tutorial go to https://github.com/wecode101/contact_mail