Monday, May 18, 2026
Core PHP

How to Send Emails in PHP Using PHPMailer: Complete Guide

Lav 9 min read
How to Send Emails in PHP Using PHPMailer: Complete Guide

Sending emails from a website is one of the most common things developers need to do. Whether it is a contact form, a welcome email, or a password reset — PHP needs a reliable way to send emails.

PHP has a built-in mail() function, but it has many problems. It often lands in spam, does not support SMTP authentication, and is hard to configure. That is why most developers use PHPMailer instead.

In this guide, you will learn exactly how to send emails in PHP using PHPMailer — step by step, in simple English.

What is PHPMailer?

PHPMailer is a free, open-source PHP library that makes sending emails easy and reliable. It supports:

  • SMTP authentication (Gmail, Outlook, Yahoo, custom servers)

  • HTML emails

  • File attachments

  • CC and BCC

  • SSL and TLS encryption

It is one of the most popular PHP libraries in the world with over 20,000 GitHub stars. Almost every PHP project that sends emails uses PHPMailer.

Requirements

Before we start, make sure you have:

  • PHP 7.2 or higher installed

  • Composer installed (PHP package manager)

  • A Gmail account (we will use Gmail SMTP in this guide)

  • A local server like XAMPP, WAMP, or a live hosting server

Step 1: Install PHPMailer Using Composer

The easiest way to install PHPMailer is with Composer. Open your terminal or command prompt, go to your project folder, and run this command:

composer require phpmailer/phpmailer 

This will download PHPMailer into a vendor folder inside your project. You will also see a composer.json file created automatically.

If you do not have Composer, download it from https://getcomposer.org.

Alternative: Manual Download

If you cannot use Composer, you can download PHPMailer directly from GitHub: https://github.com/PHPMailer/PHPMailer

Then include the files manually in your project.

Step 2: Enable Gmail SMTP (App Password)

If you are using Gmail to send emails, you need to set up an App Password. Google no longer allows your regular Gmail password for SMTP.

Here is how to create a Gmail App Password:

  1. Go to your Google Account → Security

  2. Enable 2-Step Verification (if not already enabled)

  3. Go to Security → App Passwords

  4. Select Mail as the app and Windows Computer (or Other) as the device

  5. Click Generate

  6. Copy the 16-character password Google gives you — you will use this in your PHP code

Important: Never share your App Password with anyone and never commit it to GitHub.

Step 3: Create Your PHP File

Now create a new PHP file in your project. Let us name it send_email.php.

Here is the complete basic code to send an email using PHPMailer with Gmail SMTP:

<?php 

// Load Composer autoloader
require 'vendor/autoload.php';
// Import PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Create a new PHPMailer instance
$mail = new PHPMailer(true);
try {
   // -----------------------------------------------
   // SERVER SETTINGS
   // -----------------------------------------------
   $mail->isSMTP();                                      // Use SMTP
   $mail->Host       = 'smtp.gmail.com';                 // Gmail SMTP server
   $mail->SMTPAuth   = true;                             // Enable SMTP authentication
   $mail->Username   = 'your_email@gmail.com';           // Your Gmail address
   $mail->Password   = 'your_app_password_here';         // Your Gmail App Password
   $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;   // TLS encryption
    $mail->Port       = 587;                              // TCP port for TLS

   // -----------------------------------------------
   // SENDER AND RECIPIENT
   // -----------------------------------------------
   $mail->setFrom('your_email@gmail.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

   // -----------------------------------------------
   // EMAIL CONTENT
   // -----------------------------------------------
   $mail->isHTML(true);                                  // Set email format to HTML
   $mail->Subject = 'Hello from PHPMailer!';
   $mail->Body    = '<h1>Hello!</h1><p>This email was sent using <b>PHPMailer</b> and Gmail SMTP.</p>';
   $mail->AltBody = 'Hello! This email was sent using PHPMailer and Gmail SMTP.'; // Plain text fallback

   // Send the email
   $mail->send();
    echo 'Email has been sent successfully!';
} catch (Exception $e) {
   echo "Email could not be sent. Error: {$mail->ErrorInfo}";
}

Replace your_email@gmail.com with your actual Gmail address and your_app_password_here with the App Password you generated in Step 2.


Step 4: Understanding the Code

Let us break down what each part does:

require 'vendor/autoload.php' — This loads PHPMailer automatically using Composer's autoloader. Without this line, PHP will not find the PHPMailer classes.

$mail->isSMTP() — This tells PHPMailer to use SMTP to send the email instead of the PHP mail() function.

$mail->SMTPSecure — This sets the encryption type. Use ENCRYPTION_STARTTLS for port 587 (recommended) or ENCRYPTION_SMTPS for port 465.

$mail->isHTML(true) — This allows you to send HTML content inside the email body.

$mail->AltBody — This is the plain text version of your email for people whose email clients do not support HTML.

try/catch — If anything goes wrong (wrong password, wrong server, etc.), the error is caught and displayed instead of crashing the page.

Step 5: Send Email with Attachment

Want to attach a file to your email? Just add one line:

// Add attachment
$mail->addAttachment('/path/to/your/file.pdf', 'Invoice.pdf');
// You can add multiple attachments
$mail->addAttachment('/path/to/image.jpg', 'Photo.jpg');

Add this code after $mail->addAddress(...) and before $mail->send().

Step 6: Send Email to Multiple Recipients

You can send to multiple people using addAddress(), addCC(), and addBCC():

// Multiple recipients
$mail->addAddress('person1@example.com', 'Person One');
$mail->addAddress('person2@example.com', 'Person Two');
// CC (Carbon Copy)
$mail->addCC('manager@example.com', 'Manager');
// BCC (Blind Carbon Copy)
$mail->addBCC('archive@example.com', 'Archive');

Step 7: Send Email from a Contact Form

Here is a practical example — sending an email when a user submits a contact form:

<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

   // Get and sanitize form data
   $name    = htmlspecialchars(trim($_POST['name']));
   $email   = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
    $message = htmlspecialchars(trim($_POST['message']));

   // Validate email
   if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
       die('Invalid email address.');
    }
   $mail = new PHPMailer(true);
   try {
       $mail->isSMTP();
       $mail->Host       = 'smtp.gmail.com';
       $mail->SMTPAuth   = true;
       $mail->Username   = 'your_email@gmail.com';
       $mail->Password   = 'your_app_password_here';
       $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
       $mail->Port       = 587;
       $mail->setFrom('your_email@gmail.com', 'Website Contact Form');
       $mail->addAddress('your_email@gmail.com');      // Send to yourself
        $mail->addReplyTo($email, $name);               // Reply goes to the user
       $mail->isHTML(true);
       $mail->Subject = "New Contact Form Message from $name";
       $mail->Body    = "
           <h2>New Contact Form Submission</h2>
           <p><strong>Name:</strong> $name</p>
           <p><strong>Email:</strong> $email</p>
           <p><strong>Message:</strong><br>$message</p>
        ";
       $mail->send();
       echo 'Thank you! Your message has been sent.';
   } catch (Exception $e) {
       echo "Sorry, the message could not be sent. Error: {$mail->ErrorInfo}";
   }
}
?>

<!-- HTML Contact Form -->
<form method="POST" action="">
   <input type="text"  name="name"    placeholder="Your Name"    required><br>
   <input type="email" name="email"   placeholder="Your Email"   required><br>
   <textarea name="message" placeholder="Your Message" required></textarea><br>
   <button type="submit">Send Message</button>
</form>

Common Errors and How to Fix Them

Error: SMTP connect() failed This usually means the wrong host or port. Make sure you are using smtp.gmail.com with port 587 and STARTTLS.

Error: Username and Password not accepted You are using your regular Gmail password. You must use an App Password (see Step 2).

Error: Could not instantiate mail function PHPMailer is not loaded correctly. Make sure vendor/autoload.php is included at the top.

Emails going to Spam This is common with free SMTP. To fix it: add a proper setFrom() address, use a custom domain email instead of Gmail, and consider using a transactional email service like Mailgun, SendGrid, or Amazon SES for production websites.

PHPMailer vs PHP mail() Function

Feature

PHP mail()

PHPMailer

SMTP Support

No

Yes

HTML Emails

Limited

Full support

Attachments

Difficult

Easy

Spam issues

Very common

Much less

Error handling

Poor

Excellent

Ease of use

Simple

Easy with setup

For any real-world project, PHPMailer is always the better choice.

Conclusion

Sending emails in PHP using PHPMailer is not as hard as it sounds. Once you install it with Composer and set up your Gmail App Password, you can send plain text emails, HTML emails, emails with attachments, and even handle contact form submissions — all with just a few lines of code.

Here is a quick recap of what we covered:

  • What PHPMailer is and why it is better than PHP mail()

  • How to install PHPMailer using Composer

  • How to set up Gmail SMTP with an App Password

  • How to send a basic email, email with attachment, and contact form email

  • How to fix the most common PHPMailer errors

Now you are ready to add email functionality to any PHP project. Start with the basic example, test it, and then build it into your contact form or registration system.

0 Comments

Leave a Comment