Key Takeaways
- PHPMailer enables sending HTML emails, attachments, and SMTP-authenticated emails in PHP.
- It supports Gmail, Outlook, and custom SMTP servers for secure email delivery.
- PHPMailer handles headers, error reporting, and multilingual messages automatically.
- Sending attachments and rich content is simple and developer-friendly.
Sending emails is a common feature in most PHP applications—whether it’s for user registration, order updates, or contact forms. While PHP’s built-in mail() function offers a simple way to send emails, it has limited support for HTML formatting, attachments, and reliable SMTP delivery.
PHPMailer provides a more flexible and robust alternative. In this guide, you’ll learn how to install and configure PHPMailer, connect it with Gmail’s SMTP, and send well-formatted emails with attachments using just a few lines of code.
Let’s get started…
Why Use PHPMailer Instead of PHP’s mail() Function?
PHPMailer is a third-party PHP library that provides a simple way to send emails in PHP. It offers a range of features that make it a popular alternative to PHP’s built-in mail() function, such as support for HTML emails, attachments, and SMTP authentication.
PHPMailer is easy to set up and use and provides a high level of customization and flexibility, making it a popular choice for developers who need to send emails from their PHP applications. It is also actively maintained and updated, making it a reliable and secure email option.
Here is a quick comparison between PHPMailer and PHP mail:
| Feature | PHPMailer | mail() |
|---|---|---|
| Functionality | A full-featured email library that allows sending emails with or without SMTP | A simple function that allows sending emails via the PHP mail() function |
| Complexity | More complex, but offers more features and options | Simpler, with limited options |
| SMTP Support | Supports sending email via SMTP, including authentication and encryption | Does not support sending email via SMTP |
| Attachments | Supports sending attachments | Does not support attachments |
| Error Handling | Provides detailed error messages and debugging information | Provides minimal error information |
| Security | Supports encryption and authentication when sending email via SMTP | Does not support encryption or authentication |
You might also like: How To Add SSL Certificates To Custom PHP Sites
See Performance Optimization Applied Live
On Mar 10–11, 20+ experts walk through real WordPress sites and explain each optimization decision as they make it.
Free & Live Performance Bootcamp on Mar 10-11.
Advantages of Using PHPMailer
There are several advantages to using PHPMailer over the native mail() function when sending emails in PHP:
1. Cleaner Code and Automatic Header Management
When using the mail() function, developers often need to manually create complex headers—like MIME types, content boundaries, and character encodings—which can clutter the code and introduce formatting errors. PHPMailer handles all of this behind the scenes, letting you focus on the email content instead of wrestling with syntax.
2. SMTP Support Without Server Dependency
The mail() function relies on the server’s built-in mail transfer agent (like Sendmail), which isn’t always configured or reliable. PHPMailer supports SMTP out of the box and lets you configure everything—host, port, encryption method, credentials—directly inside your PHP script. No need for server-wide changes.
3. Multilingual Error Messages
PHPMailer provides error messages in over 40 languages, making it a strong fit for applications with international users. You can easily set the language for error handling, offering a more localized and user-friendly experience.
4. SSL/TLS Encryption for Secure Delivery
Security is critical when sending emails. PHPMailer supports both SSL and TLS encryption for SMTP connections, helping protect your messages from interception during transmission.
5. HTML Emails and Plain Text Alternatives
While the mail() function can technically send HTML emails or attachments, doing so requires manually crafting multipart MIME messages. PHPMailer makes this effortless—it can send both an HTML version and a fallback plain text version with minimal setup, ensuring better compatibility across devices and email clients.
Sending Emails in PHP Using PHPMailer
Now, I’ll show you exactly how to set up and use the PHPMailer library. We’ll cover everything from getting started to sending emails with attachments via a reliable service like Gmail’s SMTP.
Prerequisites
Before we dive in, let’s get a few things in place. You’ll need:
- A Local Server like XAMPP or MAMP installed. This allows PHP to run on your machine.
- PHP 7.4 or higher (PHPMailer works with 5.5+, but newer versions are more secure and reliable).
- Composer installed (used to manage PHP libraries): Get Composer
- A text editor like VS Code or Sublime.
- (Optional but recommended) A Gmail account for testing SMTP email sending.
Step 1: Install PHPMailer via Composer
Alright, let’s get PHPMailer into your project.
Open your terminal (Command Prompt, PowerShell, or Terminal app), go to your project folder. For example, if you want a folder called email-tutorial on your desktop, you’d do something like:
cd Desktop mkdir email-tutorial cd email-tutorial

Great! You have successfully created your workspace folder and are now ready to start installing PHPMailer within it.

Now to install PHPMailer, once you’re inside your project folder, type (or copy and paste) this command and press Enter:
composer require phpmailer/phpmailer
This downloads PHPMailer and sets it up for you. You’ll see a new folder called vendor/ in your project — that’s where Composer keeps your libraries.


Step 2: Setting Up Your Files (Organizing Your Workspace)
Now that PHPMailer is in your project, let’s get our files organized. Your email-project folder should now look something like this:
Project Folder Structure:
- email-project (main folder)
- index.php – We’ll create this file for our email code
- vendor – Contains PHPMailer (automatically created by Composer)
- composer.json – Configuration file (automatically created by Composer)
Go ahead and create a new file named index.php inside your email-project folder. This is where we’ll write all our PHP code for sending emails.

Step 3: Send a Basic Email (No SMTP Yet)
Let’s start with a simple test. We’ll send an email without using a special email server (SMTP). This is just to see if PHPMailer is working correctly within your project.
Open your index.php file in your text editor and paste this code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true); // true enables exceptions
try {
// Email headers and body
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Receiver Name');
$mail->addReplyTo('[email protected]', 'Reply Name');
$mail->isHTML(true);
$mail->Subject = 'Test Email using PHPMailer';
$mail->Body = '<b>This is a test email sent from localhost using PHPMailer!</b>';
$mail->AltBody = 'This is a plain text version for non-HTML clients.';
$mail->send();
echo '✅ Email has been sent successfully!';
} catch (Exception $e) {
echo \"❌ Email could not be sent. Error: {$mail->ErrorInfo}\";
}
Save your index.php file.
Step 4: Run PHP’s Built-in Web Server
In CMD (inside your project folder), start PHP’s web server:
php -S localhost:8000
You’ll see:
PHP 8.x.x Development Server (http://localhost:8000) started

Step 5: Open Browser & Test
Go to: http://localhost:8000/index.php
What Should Happen
If everything’s wired up, you’ll either see:
- ✅ “Email has been sent successfully!” (if email transport works)
- ❌ Or: Email could not be sent. Error: … (likely if SMTP isn’t set up yet)
In my case, I’m seeing this:

Why?
By default, this setup doesn’t use SMTP — and my local PHP setup probably doesn’t have a mail server configured. That’s normal. This is why most developers use SMTP to send real emails.
We’ll now address this issue by adding SMTP next. But for now, this confirms your local server works, PHP is running, and PHPMailer is loaded.
Send Email Using SMTP (Gmail Example)
SMTP (Simple Mail Transfer Protocol) is the standard way emails are sent across the internet. Think of an SMTP server as the actual post office that picks up your letter and delivers it to the recipient’s mailbox.
Using one ensures your emails get where they need to go.
We’ll use Gmail’s SMTP server because it’s widely available and a reliable choice for sending emails.
Open your index.php file again, delete the previous code, and paste this new code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
// 1. Your Gmail Address
$mail->Username = '[email protected]';
// 2. Your App Password
$mail->Password = 'your_app_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// 4. Name Labels (Optional)
$mail->setFrom('[email protected]', 'Your Name');
$mail->addReplyTo('[email protected]', 'Your Name');
// 3. Recipient Email Address
$mail->addAddress('[email protected]', 'Friend Name');
// 5. Email Content
$mail->isHTML(true);
$mail->Subject = 'Hello from Gmail SMTP!';
$mail->Body = 'This message was sent using Gmail SMTP and PHPMailer!';
$mail->AltBody = 'Gmail SMTP version of the message.';
$mail->send();
echo '✅ Message sent using SMTP!';
} catch (Exception $e) {
echo "❌ Failed to send email. Error: {$mail->ErrorInfo}";
}
Important: App Password Setup for Gmail
If you have 2-step verification (2FA) enabled on your Gmail (and you should), you cannot use your regular Gmail password. You need to use an App Password.
Here’s how to get it:
- Visit: https://myaccount.google.com/apppasswords.
- Sign in and verify yourself.
- In the App name box, type something like: PHPMailer (or anything meaningful to you, like “My PHP Contact Form”).
- Click Create.
- Google will give you a 16-character password.

- Save it somewhere. We’ll need it when we modify our index.php file.
Customize These Fields Before Using the Code
To successfully send an email using Gmail SMTP and PHPMailer, make sure to update the following fields:
1. Your Gmail Address
Replace all instances of [email protected] with your actual Gmail address (the same one you used to generate the app password).
You’ll find this in:
$mail->Username = '[email protected]'; $mail->setFrom('[email protected]', 'Your Name'); $mail->addReplyTo('[email protected]', 'Your Name');
2. Your App Password
Now, the App Password we saved earlier, replace ‘your_app_password’ with the password you got:
$mail->Password = ‘your_app_password’;
Don’t use your actual Gmail login password here—only use the 16-character app password provided by Google.
3. Recipient Email Address
Change [email protected] to the email address where you want to send the message:
$mail->addAddress(‘[email protected]‘, ‘Friend Name’);
You can add more recipients by duplicating this line with different addresses if needed.
4. Name Labels (Optional)
Update the “Your Name” and “Friend Name” labels with whatever sender/recipient names you’d like to display in the email client.
5. Email Content
Feel free to change the subject and body text to match your own message:
$mail->Subject = 'Hello from Gmail SMTP!'; $mail->Body = 'This message was sent using Gmail SMTP and PHPMailer!'; $mail->AltBody = 'Gmail SMTP version of the message.';
Once all these fields are updated with your actual details, save the file.
Test It All
Now let’s test everything.
Open CMD and navigate to your project folder:
cd path\to\your\email-tutorial
Next, run the script:
php index.php

Success! You can confirm everything worked by checking both the sender and receiver inboxes to see if the email was delivered via Google SMTP.
Sender Inbox:

Receiver Inbox:

Send Email Attachments Using Gmail SMTP and PHPMailer
Once you’ve got your basic email script working, sending attachments is just one more line away — but let’s walk through the full setup to make sure it’s airtight.
1. Choose Your File
Place the file you want to attach in your project folder to keep paths simple.
For example, say you want to attach a PDF named sample.pdf, place it here:
C:\Users\abdulrehman\Desktop\email-tutorial\sample.pdf
Note: Your file name can be anything…doesn’t have to sample.pdf. I’ve attached a PDF guide we wrote as you can see in the screenshot below.

2. Update Your Code
In your index.php file, scroll down to where you configure the $mail object. Just after you’ve added the recipient but before sending the email, include this line:
$mail->addAttachment('sample.pdf');
This will attach the file named sample.pdf located in the same folder as your script.
3. Verify File Path (Important!)
Make sure:
- The file is not open in any program.
- The name matches exactly (case-sensitive).
- If it’s in a subfolder, include the path:
$mail->addAttachment('docs/report2024.pdf');
4. Run Your Script Again
Use CMD to navigate to the project folder:
cd C:\Users\abdulrehman\Desktop\email-tutorial
The run:
php index.php
If everything is correct, you’ll see:
✅ Message sent using SMTP!
5. Check Your Email
Open the recipient inbox and verify if you’ve received the attachment. As you can see in the screenshot below, our recipient has received the PDF file we attached in our script.

Power Your PHPMailer Projects on Fast PHP Hosting
Bring your PHP email features to life with blazing-fast PHP hosting. Launch your apps smoothly with reliable servers made for developers.
Final Thoughts
By now, you’ve seen how PHPMailer can take the pain out of sending emails in PHP. From setting up a basic script to configuring Gmail SMTP and even sending attachments, you’ve got a solid foundation to build reliable email features into your projects.
Instead of struggling with PHP’s native mail() function or dealing with server-side limitations, PHPMailer gives you a cleaner, more secure, and more flexible way to handle emails — without extra complexity.
As your applications grow, running them on a hosting platform that supports SMTP configurations and PHP libraries like PHPMailer can save you hours of troubleshooting.
With Cloudways PHP hosting, you get pre-configured PHP environments, built-in SMTP support via services like SendGrid or Mailgun, and a performance stack optimized for fast execution. That means less time on server setup — and more time writing clean, efficient code.
Frequently Asked Questions
Q. What does PHPMailer do?
PHPMailer is a popular PHP library that lets you send emails directly from your applications. It supports HTML, attachments, SMTP authentication, and makes email handling easier than using PHP’s built-in mail() function.
Q. Is PHPMailer secure?
Yes, PHPMailer supports secure email transmission through TLS and SSL encryption. When configured properly, it provides a reliable way to send sensitive information over email using authenticated SMTP servers.
Q. How do I set up Outlook SMTP with PHPMailer?
To send emails using Outlook with PHPMailer, configure these SMTP settings:
$mail->isSMTP(); $mail->Host = 'smtp.office365.com'; $mail->SMTPAuth = true; $mail->Username = '[email protected]'; $mail->Password = 'your-password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587;
These settings let you securely send emails via Outlook’s SMTP server.
Q. Does PHPMailer use Sendmail?
PHPMailer can use Sendmail, but it’s more commonly used with SMTP for better control, security, and compatibility. Sendmail is supported as a fallback or in simpler setups.
Q. What is the purpose of PHPMailer?
PHPMailer handles email sending in PHP apps. It supports plain text and HTML emails, file attachments, and SMTP authentication—making it a more capable and developer-friendly alternative to the native mail() function.
Q. What is the best method to send emails using PHP?
For basic use, PHP’s mail() function works. But for secure, flexible, and feature-rich email sending, PHPMailer is the better option. It supports SMTP, HTML content, attachments, and better error handling.
Abdul Rehman
Abdul is a tech-savvy, coffee-fueled, and creatively driven marketer who loves keeping up with the latest software updates and tech gadgets. He's also a skilled technical writer who can explain complex concepts simply for a broad audience. Abdul enjoys sharing his knowledge of the Cloud industry through user manuals, documentation, and blog posts.