How to Send Email in PHP with PHPMailer: Complete SMTP Guide (2026)

By Lyndon Bermoy

Updated on:

How to Send Email in PHP with PHPMailer: Complete SMTP Guide (2026)

PHP’s built-in mail() function is unreliable — emails end up in spam, do not send at all on shared hosting, and provide no delivery feedback. PHPMailer with a proper SMTP server is the professional solution. This guide covers everything from installing PHPMailer to sending HTML emails with attachments through Gmail SMTP.

Why PHPMailer Instead of mail()

  • SMTP authentication — PHPMailer connects to a real mail server (Gmail, Mailgun, SendGrid) with credentials, making emails deliverable
  • HTML emails — native support for multipart HTML/plain-text emails
  • Attachments — simple API for file attachments and inline images
  • Error handling — clear exceptions when sending fails, unlike mail() which silently fails
  • TLS/SSL encryption — SMTP connections are encrypted by default

Step 1: Install PHPMailer

composer require phpmailer/phpmailer

Without Composer, download PHPMailer from GitHub and include the class files manually. Composer is strongly recommended.

Step 2: Basic Email with Gmail SMTP

<?php
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

function send_email(string $to, string $subject, string $body): bool {
    $mail = new PHPMailer(true); // true = throw exceptions on error

    try {
        // SMTP configuration (Gmail):
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'youremail@gmail.com';   // Your Gmail address
        $mail->Password   = 'your_app_password';     // App password (not account password)
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        // Sender and recipient:
        $mail->setFrom('youremail@gmail.com', 'Your Name');
        $mail->addAddress($to);

        // Email content:
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = strip_tags($body); // Plain-text fallback

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email send failed: {$mail->ErrorInfo}");
        return false;
    }
}

$success = send_email(
    'recipient@example.com',
    'Welcome to CampCodes!',
    '<h1>Welcome!</h1><p>Thanks for signing up.</p>'
);
echo $success ? 'Sent!' : 'Failed — check error log';

Gmail App Password Setup

Gmail requires an App Password (not your regular account password) for SMTP access:

  1. Enable 2-Step Verification on your Google account (required for App Passwords)
  2. Go to Google Account → Security → 2-Step Verification → App Passwords
  3. Generate a new App Password — select “Mail” and your device
  4. Copy the 16-character password and use it in $mail->Password

Never store credentials in your PHP files. Use a .env file:

MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=youremail@gmail.com
MAIL_PASSWORD=your_app_password
MAIL_FROM_NAME="Your Name"
// Load with vlucas/phpdotenv:
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$mail->Username = $_ENV['MAIL_USERNAME'];
$mail->Password = $_ENV['MAIL_PASSWORD'];

HTML Email Template

function build_email_template(string $title, string $message, string $cta_url = '', string $cta_text = ''): string {
    $cta_block = $cta_url ? "<a href='{$cta_url}' style='background:#2196F3;color:#fff;padding:12px 24px;text-decoration:none;border-radius:4px;display:inline-block;'>{$cta_text}</a>" : '';
    return "<!DOCTYPE html><html><body style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;padding:20px;'>
        <h2 style='color:#1A1A2E;'>{$title}</h2>
        <p style='color:#333;line-height:1.6;'>{$message}</p>
        {$cta_block}
        <hr style='border:none;border-top:1px solid #eee;margin:30px 0;'>
        <p style='color:#999;font-size:12px;'>CampCodes · campcodes.com</p>
    </body></html>";
}

Email with Attachment

$mail->addAttachment('/path/to/invoice.pdf', 'Invoice_2026.pdf');
$mail->addAttachment('/path/to/report.xlsx');

// Inline image (displayed in email body):
$mail->addEmbeddedImage('/path/to/logo.png', 'logo_cid');
$mail->Body = '<img src="cid:logo_cid" alt="Logo"><p>See attached invoice.</p>';

Multiple Recipients

$mail->addAddress('alice@example.com', 'Alice');
$mail->addAddress('bob@example.com');             // Name optional
$mail->addCC('manager@example.com');
$mail->addBCC('archive@example.com');
$mail->addReplyTo('support@example.com', 'Support Team');

SMTP Options for Different Providers

Provider Host Port Encryption
Gmail smtp.gmail.com 587 STARTTLS
Outlook / Hotmail smtp-mail.outlook.com 587 STARTTLS
Yahoo smtp.mail.yahoo.com 465 SSL
Mailgun smtp.mailgun.org 587 STARTTLS
SendGrid smtp.sendgrid.net 587 STARTTLS
cPanel hosting mail.yourdomain.com 587 STARTTLS

Frequently Asked Questions

Why are my emails going to spam?

Using mail() without SPF/DKIM configured is the most common cause. Switch to a transactional email service (Mailgun, SendGrid) for production — they handle deliverability configuration. If using Gmail SMTP, ensure SPF records on your domain include Google’s mail servers.

READ ALSO:   PHP Cannot Redeclare Function Error

How do I test email sending without actually sending emails?

Use Mailtrap (free tier) — it is a fake SMTP server that captures sent emails and displays them in a web interface without delivering them. Perfect for development and testing.

Conclusion

PHPMailer with Gmail SMTP is the fastest way to get reliable email sending working in a PHP application. For production applications sending more than a few hundred emails per day, use a dedicated transactional email provider (Mailgun, SendGrid, or Postmark) instead of Gmail — they handle deliverability, provide tracking, and have no daily sending limits.

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

Explore Source Code Continue Tutorials Final Year Projects

Leave a Comment