DEV Community

ariba shakil
ariba shakil

Posted on

How to Set Up Contact Forms Using PHP and PHPMailer (SMTP Guide)

Learn how to configure contact forms with PHPMailer and Gmail SMTP. Step-by-step guide to set up secure email sending with App Password.

Introduction

Setting up a contact form on your website is essential for connecting with visitors. This guide will show you how to configure your contact form using PHPMailer and Gmail SMTP with a secure App Password.

What you'll learn:

  • ✅ Understanding the PHP file structure
  • ✅ Enabling 2-Step Verification on Google
  • ✅ Generating a Gmail App Password
  • ✅ Configuring submit.php file
  • ✅ Testing your contact form Let's get started! 🚀

📦 Step 1: Understand the PHP File Structure

Your template contains the following PHP files:

File Structure:

/assets/php/
├── submit.php          ← Contact form configuration
├── newsletter.php      ← Newsletter subscription configuration
├── smtp/
│   ├── Exception.php   ← PHPMailer exception handling
│   ├── PHPMailer.php   ← PHPMailer core library
│   └── SMTP.php        ← SMTP protocol handling
Enter fullscreen mode Exit fullscreen mode

🔐 Step 2: Enable 2-Step Verification on Google

Before generating an App Password, you must enable 2-Step Verification.

Steps:

  1. Login to your Google Account
  2. Click on the Security tab (left sidebar)
  3. Under "Signing in to Google", click 2-Step Verification
  4. Click Get Started
  5. Enter your password to verify your account
  6. Enter your phone number for verification
  7. Choose how to receive the code (SMS or call)
  8. Enter the verification code you receive
  9. Click Turn On

📌 Note: 2-Step Verification is required to generate App Passwords. This keeps your account secure.


🔑 Step 3: Generate Gmail App Password

Once 2-Step Verification is enabled, you can create an App Password.

Steps:

  1. Go back to Security tab
  2. Under "Signing in to Google", click App passwords
  3. Verify your account if prompted
  4. Under "Select app", choose Mail
  5. Under "Select device", choose Other (custom name)
  6. Enter a name (e.g., "Contact Form" or "My Portfolio")
  7. Click Generate

📋 Copy Your App Password:

The App Password is a 16-character code in the yellow bar. Copy it NOW and save it somewhere safe. You won't be able to see it again!

⚠️ Important: Your regular Gmail password will NOT work with PHPMailer. You MUST use the 16-character App Password generated in this step.


⚙️ Step 4: Configure submit.php File

Open /assets/php/submit.php and update the following fields:

Update These Lines:

// 1. Your Gmail ID (SMTP server)
$mail->Username = "your_email@gmail.com";

// 2. Your App Password (16-character code)
$mail->Password = "your-app-password";

// 3. Where to receive form submissions
$mail->addAddress("your_email@gmail.com", "Your Name");

// 4. Sender's email and name
$mail->setFrom('your_email@gmail.com', 'Your Name');
Enter fullscreen mode Exit fullscreen mode

Complete Example:

<?php
// SMTP configuration
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'john@gmail.com';        // ← Your Gmail
$mail->Password = 'abcd1234efgh5678';      // ← Your App Password
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Recipient
$mail->addAddress('john@gmail.com', 'John');  // ← Where email goes

// Sender
$mail->setFrom('john@gmail.com', 'John Doe'); // ← Sender info

// Subject
$mail->Subject = '(Portfolio) New Contact Info';
?>
Enter fullscreen mode Exit fullscreen mode

📧 Step 5: Update Email Subject and Settings

Customize the Subject Line:

// Change this line
$mail->Subject = "(Lorenzo) New Contact Info";

// To your own
$mail->Subject = "(MySite) New Contact Form Message";
Enter fullscreen mode Exit fullscreen mode

Customize Email Body (Optional):

// Find this section
$mail->Body = "Name: " . $_POST['name'] . "\r\n";
$mail->Body .= "Email: " . $_POST['email'] . "\r\n";
$mail->Body .= "Message: " . $_POST['message'] . "\r\n";

// You can add more fields or format it differently
$mail->Body = "📋 New Contact Form Submission\r\n";
$mail->Body .= "━━━━━━━━━━━━━━━━━━━━\r\n";
$mail->Body .= "👤 Name: " . $_POST['name'] . "\r\n";
$mail->Body .= "📧 Email: " . $_POST['email'] . "\r\n";
$mail->Body .= "📝 Message: " . $_POST['message'] . "\r\n";
Enter fullscreen mode Exit fullscreen mode

Add CC or BCC (Optional):

// CC - Copy to someone else
$mail->addCC('manager@example.com');

// BCC - Hidden copy
$mail->addBCC('backup@example.com');
Enter fullscreen mode Exit fullscreen mode

📰 Step 6: Configure newsletter.php

The newsletter subscription form works the same way. Open /assets/php/newsletter.php and apply the same settings:

// /assets/php/newsletter.php

// Same configuration as submit.php
$mail->Username = "your_email@gmail.com";      // Your Gmail
$mail->Password = "your-app-password";         // Your App Password
$mail->addAddress("your_email@gmail.com", "Your Name");
$mail->setFrom('your_email@gmail.com', 'Your Name');

// Different subject for newsletters
$mail->Subject = "(MySite) New Newsletter Signup";
Enter fullscreen mode Exit fullscreen mode

🧪 Step 7: Test Your Contact Form

Testing Methods:

Option A: Test on Localhost (XAMPP)

  1. Start Apache in XAMPP
  2. Place your files in htdocs/
  3. Visit http://localhost/your-site/
  4. Fill out the contact form
  5. Submit and check your email

Option B: Test on Live Server

  1. Upload all files to your hosting
  2. Visit your domain
  3. Fill out the contact form
  4. Submit and check your email

✅ Summary: Quick Setup Checklist

☐ 2-Step Verification enabled on Google
☐ App Password generated (16-character code)
☐ Username updated in submit.php
☐ App Password updated in submit.php
☐ addAddress updated with your email
☐ setFrom updated with your email
☐ Subject line customized
☐ newsletter.php updated the same way
☐ Form tested and working
Enter fullscreen mode Exit fullscreen mode

❓ Frequently Asked Questions

Why can't I use my regular Gmail password?
Google requires an App Password for less secure apps like PHPMailer. This is a security measure to protect your account. Your regular password will NOT work.

Where do I find the App Password?
Go to Google Account → Security → App passwords. Generate a new one and save the 16-character code immediately.

What if I lose my App Password?
You cannot retrieve it. Go to Google App passwords and generate a new one. Just update it in your submit.php file.

Why is 2-Step Verification required?
Google requires 2-Step Verification before you can generate App Passwords. It adds an extra layer of security to your account.

How do I test the form locally?
Use XAMPP or MAMP. Start the server, place your files in htdocs, and visit http://localhost/your-site/. The form will work exactly like on a live server.

Top comments (1)

Collapse
 
mohith_kumar_05846f3211f3 profile image
Mohith kumar •

Clear guide. Two additions for readers shipping this: validate and rate-limit on the server (bots find contact.php within days), and write each submission to a log table as well, so a failed SMTP call doesn't lose the lead. If someone would rather not maintain the PHP, I built chatform.in, a hosted conversational form with webhook output, but rolling your own with PHPMailer is a good way to learn it.