How to send email with HTML template using gmail SMTP in Laravel 8

In this post, I will let you know how to send email in laravel using Gmail SMTP in simple and easy steps. Laravel 8 provides several ways to send an email and you can use any email service provider. First of all, you need to install laravel and after that need to follow the following steps.

Step 1: .env Configuration

Set up the SMTP configuration in your .env file and you can find out the .env file in the root directory of the project. You can use your Gmail login email and password in MAIL_USERNAME, MAIL_PASSWORD but if you want to prevent your email password from attackers then you should use App Password. As I suggest you must use the App Password in place of the Gmail login password.

You can generate App Password from your Gmail account using a few steps. Here is a reference link: https://support.google.com/mail/answer/185833?hl=en

Note: In case, you are not able to see the .env file in the root directory of your project then you should show the hidden file because the .env file is a hidden file. If you are only able to see .env.example then need to create a .env file first.

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME={YOUR SMTP EMAIL ADDRESS}
MAIL_PASSWORD={YOUR SMTP EMAIL PASSWORD}
MAIL_ENCRYPTION=tls

Step 2: Create a Controller

Now, you need to create a controller with any name or if you want to use any existing controller then you can use it.
I am creating here controller named as UserController with the help of the following command.

php artisan make:controller UserController

Once your controller is created you are able to see some default codebase you can replace and modify by using the following code.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;

class UserController extends Controller
{
    public function testSendMail()
    {
        $data = array('name' => "User");

        Mail::send('mail', $data, function($message) {
            $message->to('toemail@example.com', 'Welcome Mail')
                    ->subject('Laravel HTML Testing Mail');
            $message->from('fromemail@example.com', 'Programming With Ajay');
        });

        dd('Mail Send Successfully');
    }
}

Step 3: Create a Route

After creating the controller you need to set a route for it. You need to add the following code to the web.php file. You can find the web.php file in the routes directory.

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('/sendemail', [App\Http\Controllers\UserController::class, 'testSendMail']);

Step 4: Create a Blade file

Now, you need to create a blade file for the email template and the name should be mail.blade.php . Because we had set the mail name in the controller. You can change it as per your requirements.

<html>
<body>
<h1>Hi, {{ $name }}</h1>
<p>Sending dynamic data Mail from Laravel.</p>
</body>
</html>

After this, you need to run the following URL, and the server URL may be different in your case. So, you must run your server base URL with the route name sendemail .

http://127.0.0.1:8000/sendemail

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.

How to send ajax request from WordPress using POST method

Ajax is a way to get, post, update, and delete data without refreshing the page. WordPress ajax is different as compared to the normal ajax in PHP. The WordPress ajax, URL is the same for all ajax requests but there is one param action and it is unique for every request. Also, the action param can define which function call on an ajax request.

Step 1: template file

Following code for the template file code. In this code, we have created a form with name and age fields and we will post this form data using ajax. Also, after posting data we will get data posted in ajax response and print it on the same page. Using form ID sendAjaxFormId we will post this form and after the ajax response display data using IDs responseName responseAge .

<form id="sendAjaxFormId">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name">
</div>
<div class="form-group">
<label>Age</label>
<input type="text" class="form-control" id="age" placeholder="Enter age">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<p>Entered Name: <span id="responseName"></span></p>
<p>Entered Age: <span id="responseAge"></span></p>

Step 2: custom.js file

In the custom.js file, we have JQuery code to send Ajax request to the function.php file and return back the response in the same file. Some information about Ajax params:

formData => used to send/post data.

url => to set Ajax request URL (it’s common for all ajax requests).

type => Ajax request method (it can get, post, delete, etc)

dataType => Ajax request and response data type.

data => data param contains action, posted data two params. Action should be unique for every request.

success => if the request is successfully processed, then get a response in success function/param.

error => if the request does not process successfully or occurred error during this then the error can catch in the error function.

jQuery(document).ready(function() {
    jQuery('#sendAjaxFormId').submit(function(ev) {
        ev.preventDefault();
        var formData = {
            name: jQuery('#name').val(),
            age: jQuery('#age').val()
        }
        
        jQuery.ajax({
            url: ajaxObject.ajaxUrl,
            type: "post",
            dataType: "json",
            data: {
                action: 'form_post_data',
                data: formData
            },
            success: function(response) {
                console.log(response);
                jQuery('#responseName').html(response.data.name);
                jQuery('#responseAge').html(response.data.age);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });    
});

Step 3: function.php

In this file, we have done two things. First, handle ajax request and second localize PHP variables to pass in JS file.

wp_enqueue_scripts hook is used to enqueue the JS file. wp_localize_script is used to pass params to custom.js file. So, we passed the Ajax URL in the following code.

wp_ajax_form_post_data is a combined hook. wp_ajax_ is common for all requests and form_post_data is an action that is passed from the custom.js file. wp_ajax_nopriv_ hook allows running requests by unauthenticated or any user. So, you can miss or remove this from your code.

In the handleFormPostData method, we checked and return the same posted data in JSON format. Because we set dataType JSON while sending Ajax from the JS file.

add_action('wp_enqueue_scripts', 'myScriptEnqueue');

function myScriptEnqueue() {
    wp_enqueue_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'));
    wp_localize_script(
        'custom-js',
        'ajaxObject',
        array('ajaxUrl' => admin_url('admin-ajax.php'))
    );
}

add_action('wp_ajax_form_post_data', 'handleFormPostData');
add_action('wp_ajax_nopriv_form_post_data', 'handleFormPostData');

function handleFormPostData() {
    $response = array();
    $response['message'] = "Error";
    $response['data'] = [];

    if (isset($_POST['data']) && !empty($_POST['data'])) { 
        $response['message'] = "Success";       
        $response['data'] = $_POST['data'];
    }
        
    echo json_encode($response);
    wp_die();
}

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.