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

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

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

Setting up a contact form requires PHPMailer library, Gmail SMTP configuration, and a 16-character App Password. Never use your regular Gmail password.
PHP Developer

๐Ÿ“ฆ Step 1: Understand the PHP File Structure

Your template contains /assets/php folder with submit.php for contact form and newsletter.php for newsletter subscription. Also includes PHPMailer library files: Exception.php, PHPMailer.php, and SMTP.php.

๐Ÿ” Step 2: Enable 2-Step Verification on Google

Login to your Google Account, go to Security tab, click on 2-Step Verification, click Get Started, enter your password, verify your phone number, and enter the verification code to enable it.

๐Ÿ”‘ Step 3: Generate Gmail App Password

After enabling 2-Step Verification, go to App passwords under Signing in to Google. Select 'Mail' from Select app and 'Other' from Select device, give it a name like 'Contact Form', and click Generate. Copy the 16-character code.

โš™๏ธ Step 4: Configure submit.php File

Open /assets/php/submit.php. Update Username with your Gmail ID, Password with your 16-character App Password, addAddress with the email where you want to receive form submissions, and setFrom with your sender email and name.

๐Ÿ“ง Step 5: Update Email Subject and Settings

Change the Subject line to something like '(YourSite) New Contact Form Message'. You can also customize the email body template and add CC/BCC recipients if needed.

๐Ÿ“ฐ Step 6: Configure newsletter.php Similarly

Open /assets/php/newsletter.php and apply the same SMTP settings - Username, Password, addAddress, and setFrom. This ensures your newsletter subscription form also works properly.

๐Ÿงช Step 7: Test Your Contact Form

Run your site on localhost using XAMPP or upload to live server. Fill out the contact form and submit. Check your recipient email inbox. The email should arrive within seconds using SMTP.