In this example, we will create simple contact form. When user submit those details instad of storing those data we will directly send it to responsible person using google mail.
Sending email is essential part of every web application and there are plenty of ways or services to send E-mail in Laravel application. The mail function is essential for these tasks, to register or notify the users, password reset link and much more.
The benefits of using SMTP server cannot be over emphasized, with an SMTP server we can send email from our local server. Thus, giving us the ability to test the email functionality on the local server itself.
In this tutorial, we will create simple contact us form and send data of that form using Gmail SMTP.
Main Reason is when we use google SMTP, it make sure user receive mail into inbox instand of spam folder. In addition it's free to use and you don't need to purchase mail service for small project. It provides free 100 mails per day.
Now days, It's perfect choice for email communication because their server's stability and consistent performance and grate userbase.
For your better understanding, we have divided our application into some parts :
Note : If you already has Laravel application then you can skip first and second step.
First, open terminal and create new Laravel application using below command :
Let's configure database for our application. If you have don't have any database then create a new one. After creating database open .env file from root directory of your project. if .env file is missing from project then copy content from .env.example and create file. .env file defines many common environment variables
First of all let's configure our mail, for that you have to configure mail driver, mail host, mail port, Gmail credentials like below example
Let's head back to terminal at root directory of project and enter below command :
.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mail_address
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=admin@example.com
MAIL_FROM_NAME="${APP_NAME}"
In the above settings , we configured MAIL_DRIVER as smtp, MAIL_HOST for Gmail as smtp.gmail.com, MAIL_ PORT for Gmail as 587 and MAIL_ENCRYPTION method as tls.
Since we are using Gmail SMTP, we need to change some security settings on our Google account, to give access to less secured applications.
Before starting, first of all we need to modify/change some security setting into our Gmail account.
Log in to your GMail account. Now Click on your profile picture and then click on "Manage Your Google Account". Then Under Security tab, Select "Less secure app access". At last click to "Turn on access (not recommended)".
In Laravel, each type of mail sent by your application is referred as Mailable class. All Mailable classes are stored at app/Mail directory into your project. Don't worry if it is not in your application, it's automatically created while creating mailable class.
To create mailable class with is markdown, enter below command into your terminal :
php artisan make:mail ContactMail
This command will create app/Mail/ContactMail.php and resources/views/mail/contact-mail.blade.php files. Mailable class will handle logic for mail. While view will send through mail to user.
app\Mail\ContactMail.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
return $this->subject('Inquiry From '.$this->data['name'].' ('.$this->data['email'].')' )
->markdown('mail.contact-mail')
->with('data', $this->data);
}
}
In simple terms when user submit form controller call mailable class and pass all user entered data as array to construct method while build method will create mail object and generate view with markdown() function.
Next thing you need is a controller which will validate user inputs and pass create mail object and trigger mail using out google mail configuration. To create the controller, run this Artisan command:
php artisan make:controller MailController
It will create a new file called MailController.php in the app/Http/Controllers directory. Now you need to modify this newly created controller as per requirement :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactMail;
class MailController extends Controller
{
public function ContactMail(Request $request){
$validated = $request->validate([
'name' => 'required|max:255',
'email' => 'required|email',
'phone' => 'required',
]);
$data = $request->input();
Mail::to('admin@example.com')->send(new ContactMail($data));
return back()->with('success', 'Thanks for contacting us!');
}
}
Here, we have created ContactMail() function. First of all this function validate user input and then get those inputs into an array and then send those data through mail. Here, you need to replace receiver email address for testing.
Now we have to create views for get user input as well as mail template. We will get user input into contact form so let's create it first.
let's navigate to views directory and create new file contact.blade.php. In this view file, we will set form which take name, email, phone number and message from user. so let's modify it :
resources\views\contact.blade.php
For modify markdown or mail template open resources\views\mail\contact-mail.blade.php. This file is already created with Mailable class. Let's make some changes to view.
resources\views\mail\contact-mail.blade.php
@component('mail::message')
# Inquiry From {{$data['name']}}
{{$data['message']}}
Call : {{$data['phone']}}
{{ config('app.name') }}
@endcomponent
Last thing we need to add is create route which will all user routing. For this application we need to define 2 routes. First route will display contact form and send route will handle sending mail functionality.
routes\web.php
<?php
use App\Http\Controllers\MailController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('contact-us', function(){
return view('contact');
});
Route::post('/contact-mail', [MailController::class, 'ContactMail'])->name('contact.mail');
php artisan serve
open below URL into your browser :
http://127.0.0.1:8000/contact-us
Fill up form with dummy data and hit enter. It will trigger mail from configured Gmail address to your specific address. you can change receiver address from controller.
Feel Free to comment if you have any issue with this example or facing any error while running.
Ask anything about this examples