Short answer: Install PHPMailer with Composer, turn on 2-Step Verification in your Google Account, create a Gmail app password, then connect to smtp.gmail.com on port 587 with STARTTLS, using your Gmail address as the username and the app password as the password.
Sending email from a PHP website or a local server is easy with PHPMailer. PHP's built-in mail() function depends on your server setup and often lands in spam, while PHPMailer connects to a real SMTP server such as Gmail with proper authentication and encryption.
Important: "Less secure apps" no longer works
Older tutorials tell you to enable "Less secure apps" in your Google Account. Google has switched that option off, so those steps fail with an authentication error. This guide uses an app password, which is the current method.
Key Takeaways:
- Install PHPMailer with Composer in one command
- Use a Gmail app password, not your normal password
- Gmail SMTP: smtp.gmail.com, port 587 (STARTTLS) or 465 (SSL)
- Fix the most common authentication and connection errors
Why Use PHPMailer?
PHPMailer simplifies sending email from PHP. Here is how it compares with the built-in function:
PHP mail() Function
- Depends on the server's mail setup
- No SMTP login
- HTML and attachments need manual headers
- Only returns true or false on errors
- Often ends up in spam
PHPMailer
- SMTP authentication built in
- HTML and plain text bodies
- Attachments in one line
- Detailed error messages
- SSL/TLS encryption
Step 1: Install PHPMailer
You need PHP, a local server (for example WAMP on Windows, XAMPP or any web host) and Composer, a PHP dependency manager.
Installation Steps:
- Install Composer: download the installer for your operating system from the official Composer website.
- Install PHPMailer: open a terminal in your project folder and run:
composer require phpmailer/phpmailer
This creates a vendor folder and a vendor/autoload.php file. No Composer? Download PHPMailer from its GitHub repository, copy the src folder into your project, and include Exception.php, PHPMailer.php and SMTP.php with require.
Step 2: Create a Gmail App Password
Google no longer accepts your normal password from apps. You create a special 16-character app password instead:
- Open your Google Account security settings.
- Turn on 2-Step Verification if it is not already on.
- Open the App passwords page.
- Enter a name such as
PHPMailerand click Create. - Copy the 16-character password. Google shows it only once. Remove any spaces when you paste it into your code.
If you do not see the App passwords option, 2-Step Verification is probably off, or your account is managed by an organization that disabled it.
Gmail SMTP settings
- SMTP server:
smtp.gmail.com - Username: your full Gmail address
- Password: the app password
- Port:
587(STARTTLS) or465(SSL)
Step 3: Write the PHP Code
Create a file named send-mail.php in your project folder and paste this code. Replace the email addresses and the app password.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require __DIR__ . '/vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your-email@gmail.com';
$mail->Password = 'your-16-character-app-password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Recipients
$mail->setFrom('your-email@gmail.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient');
// Content
$mail->isHTML(true);
$mail->Subject = 'Test email from PHPMailer';
$mail->Body = '<h1>It works!</h1><p>Sent with PHPMailer and Gmail SMTP.</p>';
$mail->AltBody = 'It works! Sent with PHPMailer and Gmail SMTP.';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
What each part does:
new PHPMailer(true)turns on exceptions so errors are caught in thecatchblock.Host,PortandSMTPSecureare Gmail's server settings.Usernameis your full Gmail address andPasswordis the app password.AltBodyis the plain text version for email apps that do not show HTML.
Step 4: Test It
- Start your local server.
- Open
http://localhost/your-folder/send-mail.phpin your browser, or runphp send-mail.phpin the terminal. - You should see Message has been sent. Check the recipient's inbox and spam folder.
Port 587 vs 465
| Port | Encryption | PHPMailer setting |
|---|---|---|
587 | STARTTLS (recommended) | PHPMailer::ENCRYPTION_STARTTLS |
465 | SSL/TLS (SMTPS) | PHPMailer::ENCRYPTION_SMTPS |
If your host or network blocks port 587, switch to 465:
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // implicit SSL
$mail->Port = 465;
Debugging with SMTPDebug
When an email does not send, turn on debug output to see exactly where the SMTP conversation fails:
use PHPMailer\PHPMailer\SMTP;
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // shows the full SMTP conversation
// Remove this line (or set it to 0) before going live.
Bonus: Send Email from a Contact Form
This example reads a form, validates the input, and sends the message to yourself. The visitor's address goes in Reply-To, because Gmail always sends from your own account.
contact.html
<form method="post" action="contact.php">
<label>Name <input type="text" name="name" required></label>
<label>Email <input type="email" name="email" required></label>
<label>Message <textarea name="message" required></textarea></label>
<button type="submit">Send</button>
</form>
contact.php (credentials come from environment variables, see the security tips below)
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require __DIR__ . '/vendor/autoload.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
$message = trim($_POST['message'] ?? '');
if ($name === '' || !$email || $message === '') {
exit('Please fill in all fields with a valid email address.');
}
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = getenv('GMAIL_USER');
$mail->Password = getenv('GMAIL_APP_PASSWORD');
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$mail->setFrom(getenv('GMAIL_USER'), 'Website Contact Form');
$mail->addAddress(getenv('GMAIL_USER'));
$mail->addReplyTo($email, $name);
$mail->Subject = 'New message from ' . $name;
$mail->Body = "Name: $name\nEmail: $email\n\n$message";
$mail->send();
echo 'Thanks! Your message was sent.';
} catch (Exception $e) {
error_log($mail->ErrorInfo);
echo 'Sorry, the message could not be sent.';
}
}
Common Errors and Fixes
| Error | Cause and fix |
|---|---|
SMTP Error: Could not authenticate or 535 Username and Password not accepted | You used your normal password or a wrong app password. Create an app password (2-Step Verification must be on) and remove spaces. |
SMTP connect() failed or connection timeout | A firewall or host blocks the port. Try port 465 with ENCRYPTION_SMTPS. Some shared hosts block outgoing SMTP, so ask your host. |
Class 'PHPMailer\PHPMailer\PHPMailer' not found | The autoload path is wrong or Composer has not run. Check that vendor/autoload.php exists and the require path matches. |
certificate verify failed on localhost | PHP has no CA bundle. Download cacert.pem and set openssl.cafile in php.ini, then restart the server. |
| Email goes to spam | Send from the same Gmail address you log in with, and add a clear subject and AltBody. On a custom domain, set up SPF and DKIM. |
Security Tips
- Never put your app password in public code. Do not commit it to GitHub. Store it in an environment variable or in a config file outside your web root:
$mail->Username = getenv('GMAIL_USER');
$mail->Password = getenv('GMAIL_APP_PASSWORD');
- Revoke the app password from your Google Account if it is ever exposed.
- Validate all form input, and never trust user data in headers.
- Gmail is fine for small projects and testing. For large or commercial volume, use a transactional email service.
Watch the Video Tutorial
If you prefer a visual guide, watch the video below. The Gmail account steps have changed since it was recorded, so follow the app password steps in this article for the account setup.
Learn how to send emails with PHPMailer and Gmail SMTP in under 10 minutes.
Additional Resources
For more information and advanced configurations, check out these resources:
- Source Code for this Tutorial - Download the complete working example
- Gmail SMTP Settings - Official Gmail SMTP documentation
Frequently Asked Questions
Which port should I use with PHPMailer and Gmail, 587 or 465?
Use port 587 with STARTTLS or port 465 with SSL. Both work with smtp.gmail.com. This tutorial uses 587. Match the encryption setting to the port you choose.
Can I still use "Less secure apps" with Gmail?
Older tutorials tell you to turn it on, but you should not rely on it. Google's help page says that with 2-Step Verification on, some less secure apps may be blocked, and an app password lets a blocked app sign in. Use an app password, or "Sign in with Google" if your app supports it.
Why do I get "Could not authenticate" in PHPMailer?
The most common cause is using your normal Gmail password instead of an app password. Also check that 2-Step Verification is on, that you copied the 16-character app password correctly, and that you did not change your Google password afterwards, because that revokes all app passwords.
Why can't I see "App passwords" in my Google account?
Google says you may not see the option if 2-Step Verification is set up only with security keys, if you use a work or school account, or if Advanced Protection is on. Check that 2-Step Verification is on, then open myaccount.google.com/apppasswords.
Is it safe to put a Gmail app password in my PHP code?
Keep it out of your code and out of public repositories. Store it in an environment variable or a config file outside the public folder, and remove the app password from your Google account if you no longer use it.


