Loading.......
Loading...

How to send email via Gmail SMTP using ajax and php

Posted on 5th December, 2025
GMAIL SMTP MAILER SEND EMAIL VIA GMAIL SEND EMAIL VIA SMTP GMAIL MAILER SMTP MAILER
Sending email via Gmail SMTP is a robust way to ensure your emails don't end up in spam folders. Because standard PHP `mail()` is often blocked by servers, using a library like PHPmailer combined with AJAX for a seamless user experience is the industry standard.

Here is a step-by-step guide to setting this up.

Prerequisites

1. PHPmailer: You should not write raw SMTP code from scratch. PHPmailer handles the complex protocol negotiations.
2. Google App Password: You cannot use your standard Gmail password anymore due to security protocols (2FA). You must generate an "App Password."

Step 1: Configure Google Security (Crucial)

Before writing code, you must allow your script to access your Gmail account.
1. Go to your Google Account Settings.
2. Navigate to the Security tab.
3. Ensure 2-Step Verification is turned ON.
4. Search for "App Passwords" (or look under 2-Step Verification).
5. Create a new App Password (name it "Website SMTP").
6. Copy the 16-character code. This is the password you will use in your PHP script.

Step 2: Install PHPmailer

The best way is via Composer. Run this in your project terminal:

BASH CODE

 composer require phpmailer/phpmailer
If you don't have Composer, you can manually download the PHPmailer source code from GitHub and include the `src` files manually, but Composer is highly recommended.

Step 3: The Backend (PHP Script)

Create a file named `send_mail.php`. This script will receive the AJAX data and talk to Gmail.

PHP CODE

<?php
// send_mail.php
use PHPmailer\PHPmailer\PHPmailer;
use PHPmailer\PHPmailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// Initialize response array
$response = ['status' => 'error', 'message' => 'Something went wrong.'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// 1. Sanitize Input
$name = htmlspecialchars(strip_tags($_POST['name']));
$email = filter_var($_POST['email'], FILTER_SANITIZE_Email);
$message = htmlspecialchars(strip_tags($_POST['message']));
// 2. Setup PHPmailer
$mail = new PHPmailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@gmail.com'; // YOUR Gmail
$mail->Password = 'xxxx xxxx xxxx xxxx'; // YOUR APP PASSWORD (Not login password)
$mail->SMTPSecure = PHPmailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Recipients
$mail->setFrom('your_email@gmail.com', 'mailer Service');
$mail->addAddress('recipient_email@example.com'); // Where you want to receive the email
$mail->addReplyTo($email, $name); // So you can reply to the user
// Content
$mail->isHTML(true);
$mail->Subject = 'New Contact Form Message from ' . $name;
$mail->Body = "<b>Name:</b> $name <br><b>Email:</b> $email <br><b>Message:</b><br>$message";
$mail->AltBody = "Name: $name \nEmail: $email \nMessage: $message";
$mail->send();
$response['status'] = 'success';
$response['message'] = 'Email has been sent successfully!';

} catch (Exception $e) {
$response['message'] = "Message could not be sent. mailer Error: {$mail->ErrorInfo}";
}
} else {
$response['message'] = "Invalid Request Method";
}
// Return JSON response
header('Content-Type: application/json');
echo json_encode($response);
?>

Step 4: The Frontend (HTML & AJAX)

We will use Vanilla JavaScript (Fetch API) for the AJAX request. It is modern, lightweight, and doesn't require jQuery.

Create an index.html file then copy and paste the below code into the index.html file and save it

HTML CODE

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
<style>
body { font-family: sans-serif; padding: 20px; }
form { max-width: 400px; margin: 0 auto; }
input, textarea { width: 100%; margin-bottom: 10px; padding: 8px; }
button { padding: 10px 20px; background: #28a745; color: #fff; border: none; cursor: pointer; }
#statusMessage { margin-top: 10px; font-weight: bold; }
.success { color: green; }
.error { color: red; }
</style>
</head>
<body>
<form id="contactForm">
<h2>Contact Us</h2>
<input type="text" name="name" id="name" placeholder="Your Name" required>
<input type="email" name="email" id="email" placeholder="Your Email" required>
<textarea name="message" id="message" rows="5" placeholder="Your Message" required></textarea>
<button type="submit" id="submitBtn">Send Message</button>
<div id="statusMessage"></div>
</form>
<script>
const form = document.getElementById('contactForm');
const statusMsg = document.getElementById('statusMessage');
const submitBtn = document.getElementById('submitBtn');
form.addEventListener('submit', function(e) {
e.preventDefault(); // Stop page reload
// Change button text to indicate processing
submitBtn.textContent = 'Sending...';
submitBtn.disabled = true;
statusMsg.textContent = '';
statusMsg.className = '';
// Gather Form Data
const formData = new FormData(this);
// Send AJAX Request
fetch('send_mail.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
statusMsg.textContent = data.message;
statusMsg.className = 'success';
form.reset(); // Clear the form
} else {
statusMsg.textContent = data.message;
statusMsg.className = 'error';
}
})
.catch(error => {
console.error('Error:', error);
statusMsg.textContent = 'An unexpected error occurred.';
statusMsg.className = 'error';
})
.finally(() => {
submitBtn.textContent = 'Send Message';
submitBtn.disabled = false;
});
});
</script>
</body>
</html>

How it works (Visual Flow)

1. User clicks "Send" on the HTML form.
2. JavaScript intercepts the click, prevents the page from reloading, and collects the data.
3. AJAX (Fetch) sends the data asynchronously to `send_mail.php`.
4. PHP validates the data and uses PHPmailer to connect to `smtp.gmail.com`.
5. Gmail authenticates the "App Password" and delivers the email.
6. PHP returns a JSON response (`success` or `error`).
7. JavaScript receives the JSON and updates the UI (e.g., "Email Sent!").

Common Troubleshooting

Issue: Authentication Error
Solution: Double-check your Google App Password. Do not use your regular login password.

Issue: Port Issues
Solution: Ensure your server/hosting allows outbound connections on Port 587. Some shared hosts block this.

Issue: JSON Parse Error
Solution: Ensure `send_mail.php` does not `echo` anything other than the final JSON. PHP Warnings appearing on screen will break the JSON.

Thank You!
The Vasplus Team.
Post Comment
Press Enter to send
No comment yet.

Submit your Job or Project Today!

We can help you turn your idea into reality, take over your existing project, or extend your current development team.

Submit your idea job or project below and we will follow up with you shortly.

OUR OBJECTIVE

Our objective is to reach a place where our services will be highly regarded by businesses from various industrial domains for building their innovative busines solutions with our cutting-edge technological expertise, interactive designs and uncompromised quality.

OUR MISSION

We aspire to help businesses ranging from startups to enterprises, who reach out to us with their requirements, in achieving great lengths, expanding their reach, upscaling their products, and generate a large user-base with our outstanding and cost-effective services.

Please Wait....
Please Wait...