🚀 📧 Send Emails using Gmail SMTP (PHP)
🟢 Step 1: Download PHPMailer
👉 Go to:
https://github.com/PHPMailer/PHPMailer
Click Code → Download ZIP
Extract and copy the folder into your project.
📁 Structure
contact-form/
│── PHPMailer/
│── index.php
│── send.php
🟡 Step 2: Enable Gmail SMTP Access
🔐 Important (Very Important Step)
- Go to: https://myaccount.google.com/security
- Enable 2-Step Verification
- Then go to:
👉 https://myaccount.google.com/apppasswords - Generate App Password
👉 Select:
- App: Mail
- Device: Other → type “PHP”
✅ Copy the 16-digit password
🔵 Step 3: Create Email Sending File (send.php)
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';$mail = new PHPMailer(true);try {
// 🔹 Server settings
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'yourgmail@gmail.com'; // your Gmail
$mail->Password = 'your_app_password'; // App Password
$mail->SMTPSecure = 'tls';
$mail->Port = 587; // 🔹 Sender & Receiver
$mail->setFrom('yourgmail@gmail.com', 'Your Website');
$mail->addAddress('receiver@gmail.com'); // where you want to receive // 🔹 Content
$mail->isHTML(true);
$mail->Subject = 'New Contact Form Message';
$mail->Body = '<b>Hello!</b> This is a test email from PHP SMTP.'; $mail->send();
echo "✅ Email sent successfully!";} catch (Exception $e) {
echo "❌ Email failed: {$mail->ErrorInfo}";
}
🟣 Step 4: Connect with Contact Form
Update your process.php:
$messageBody = "
Name: $name <br>
Email: $email <br>
Message: $message
";$mail->Body = $messageBody;
🔴 Step 5: Test It
- Run project on localhost / live server
- Submit form
- Check your email inbox 📩
⚠️ Common Errors & Fixes
❌ 1. Authentication Failed
👉 Fix:
- Use App Password, NOT Gmail password
❌ 2. Could not connect to SMTP
👉 Fix:
- Check internet
- Use correct port (587)
❌ 3. SSL Error
👉 Try:
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
🔐 Security Tips (Important)
✔ Never expose password in public code
✔ Use .env file (advanced)
✔ Validate form before sending email
✔ Limit spam (use reCAPTCHA)
🎯 Pro Version (Best Practice)
Use this config:
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
🚀 Final Result
Now your contact form can:
✅ Send real emails
✅ Work like professional websites
✅ Be used for clients / business






