Wondering how to Create a Laravel Contact Form to Send Emails with SendGrid? We can help you.
Having a contact form on the website makes it easy for the visitors on the web page to contact us directly.
Here at Bobcares, we often get requests from our clients to set up a contact form to send emails as a part of our Server Management services.
In this article, we will see how our Expert Support Engineers create a Laravel contact form to send an email with the help of SendGrid.
Steps to Create a Laravel Contact Form to Send Emails with SendGrid
We know that Laravel is a free, open-source PHP framework, based on Symfony and helps in creating web applications.
It is necessary to have an SMTP server for sending emails through the contact form.
For this, we will use SendGrid which is a cloud-based SMTP provider that allows us to send email without having to maintain email servers.
A SendGrid account and a fully registered domain name pointed to the server are the prerequisites for this setup.
We will see the steps that our Support Techs follow for creating a Laravel contact form to send emails with SendGrid.
Creating the Sender Identity
First, we will have to verify the ownership of the domain name in SendGrid so that it allows us to send emails.
We can follow the below steps to verify the domain.
1. First, go to the SendGrid account
2. And take the Dashboard.
3. Then click on Authenticate your Domain.
4. After this we need to specify our DNS host and choose to brand the links for the domain.
5. Select No for email link branding.
6. Then click Next and on the next page, specify the domain name.
7. Finally, we will add the DNS records provided by SendGrid to complete their verification process.
8. After adding the DNS records to the DNS zone, we can go back to SendGrid and click the Verify button.
9. Now we will use the Laravel .env file to generate an API key.
10. We will click on API Keys first and then click on the Create API Key button.
11. For security, we will set the API Key Permissions to Restricted Access.
12. After that, we will add the Mail Send permissions.
13. Finally, click on the Create & View button to get the API key.
We will save this API key for further use.
Configuring the SMTP Details
The .env file in Laravel will store various configuration options for our application environment.
Using the following steps we can configure the SMTP details:
1. We will go to the /var/www/travellist directory to access the .env file with the following command:
$ cd /var/www/travellist
2. After that, open the .env file:
$ nano .env
3. To change the MAIL variables we will alert the MAIL_ settings and configure the variables given below:
. . .
MAIL_MAILER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=sendgrid_api_key
MAIL_ENCRYPTION=tls
. . .
4. Save and exit the file.
Creating the Controller
The controller we create will handle our POST and GET requests for the contact form page.
1. We will use the following artisan command in order to create a controller called ContactController in Laravel:
$ php artisan make:controller ContactController
2. Then run the following to edit the ContactController.php file:
$ nano app/Http/Controllers/ContactController.php
3. To include the Laravel Mail facade add the following:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
4. Then we will add the method that will handle our GET requests and return the contact page view:
class ContactController extends Controller
{
public function contact(){
return view('contact');
}
}
5. Finally, we will add a method that will handle the POST requests and send out the emails:
class ContactController extends Controller { public function contact(){ return view('contact'); } public function contactPost(Request $request){ $this->validate($request, [ 'name' => 'required', 'email' => 'required|email', 'comment' => 'required' ]); Mail::send('email', [ 'name' => $request->get('name'), 'email' => $request->get('email'), 'comment' => $request->get('comment') ], function ($message) { $message->from('youremail@your_domain'); $message->to('youremail@your_domain', 'Your Name') ->subject('Your Website Contact Form'); }); return back()->with('success', 'Thanks for contacting me, I will get back to you soon!'); } }
6. Save and exit the file.
We will handle the validation inside the contactPost() method with the $this->validate() method.
Inside the validation method, we will specify that the name, email, and comment are required.
When validation is successful, the Mail::send() method constructs the email body and subject and then sends out the email.
Finally, if the email is sent successfully, we will return a success message that displays to the users.
[Need assistance to create controller? We are happy to help you!]
Creating the Routes
Laravel routes allow us to create SEO-friendly URLs for our application.
Here we will create two routes in our routes/web.php file to use the methods we have set up.
1. First, open routes/web.php with the following command:
$ nano routes/web.php
2. Next we will add the GET route at the bottom of the file:
<?php
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::get('/contact', 'ContactController@contact')->name('contact');
3. After that we will add a POST route and map it to our contactPost method, which will handle the user contact form submissions:
<?php
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::get('/contact', 'ContactController@contact')->name('contact');
Route::post('/contact', 'ContactController@contactPost')->name('contactPost');
4. Finally, save and exit the file.
Creating the Blade Views
1. First, we will create a file resources/views/contact.blade.php:
$ nano resources/views/contact.blade.php
2. Then add the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form with Laravel and SendGrid</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<div class="container">
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<form method="POST" action="/contact">
@csrf
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="email">Email address</label>
<input name="email" type="email" class="form-control" id="email" aria-describedby="emailHelp"
placeholder="Enter your email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="name" placeholder="Your name">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="exampleInputPassword1">Comment</label>
<textarea name="comment" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
<span class="text-danger">{{ $errors->first('comment') }}</span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
3. Save and exit this file.
4. After that, we will create our email view by opening the resources/views/email.blade.php file with the following command:
$ nano resources/views/email.blade.php
5. Then add the following content:
Inquiry from: {{ $name }}
<p> Email: {{ $email }} </p>
<p> Message: {{ $comment }} </p>
6. Save and exit the file.
[Need assistance? We are happy to help you!]
Conclusion
To conclude, we saw the steps our Support Engineers follow to create a Laravel contact form to send emails with the help of SendGrid.
0 Comments