Using PHPMailer Without Composer With SMTP Configurations and Form Handling Print

  • PHPMailer, Composer, Form Mailer, FormMailer
  • 233

This guide explains how to manually integrate PHPMailer into your PHP project without dependency managers, handle secure HTML form data extraction, and deploy drop-in configurations for Gmail, Microsoft 365, and SendGrid.

1. Core Manual Installation

To use PHPMailer manually, you must explicitly download and include its dependencies in a specific order.

  • Download the source files from the official PHPMailer GitHub Repository.
  • Extract the ZIP and copy the src/ directory into your project. Rename it to PHPMailer/.
  • Ensure your project structure matches the layout below:
your-project/
│
├── index.php (Your HTML Form and PHP Processing Script)
└── PHPMailer/
    ├── Exception.php
    ├── PHPMailer.php
    └── SMTP.php
CRITICAL REQUIREMENT: The file Exception.php must always be required first. PHPMailer will fail with a fatal error if this sequence is altered.

2. Configuration Profiles

Replace the server settings block in the complete code script with one of these validated vendor configurations:

Provider Host Port / Encryption Authentication Requirement
Gmail smtp.gmail.com 587 (STARTTLS) or 465 (SMTPS) Google Account App Password (2FA Required)
Microsoft 365 smtp.office365.com 587 (STARTTLS) App Password or SMTP Auth enabled in Admin Center
SendGrid smtp.sendgrid.net 587 (STARTTLS) API Key (Username is always apikey)

Option A: Gmail Integration

$mail->isSMTP();
$mail->Host       = '://gmail.com';
$mail->SMTPAuth   = true;
$mail->Username   = 'your_gmail@gmail.com';
$mail->Password   = 'xxxx xxxx xxxx xxxx'; // Must be a 16-character App Password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port       = 587;

Option B: Microsoft 365 / Outlook Integration

$mail->isSMTP();
$mail->Host       = '://office365.com';
$mail->SMTPAuth   = true;
$mail->Username   = 'your_email@outlook.com'; // Or corporate M365 email
$mail->Password   = 'your_m365_app_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port       = 587;

Option C: SendGrid API SMTP Integration

$mail->isSMTP();
$mail->Host       = 'smtp.sendgrid.net';
$mail->SMTPAuth   = true;
$mail->Username   = 'apikey'; // This literal string is mandatory for all accounts
$mail->Password   = 'SG.your_actual_api_key_here'; 
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port       = 587;

3. Form Security & Variable Parsing

When connecting an HTML form to a mailer script, you must sanitize and validate user input to protect your application from header injection and spam attacks. The code below incorporates htmlspecialchars() and filter_var() to secure values before feeding them into PHPMailer variables.

4. Complete Ready-to-Run Interactive Code Template

Copy this single self-contained code block into your index.php file. It renders the front-end form, safely parses incoming data fields, and submits the payload through your chosen SMTP server.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Track submission states for display feedback
$statusMessage = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // 1. Core manual requirements
    require 'PHPMailer/Exception.php';
    require 'PHPMailer/PHPMailer.php';
    require 'PHPMailer/SMTP.php';

    // 2. Parse and sanitize inbound form variables
    $clientName    = isset($_POST['sender_name']) ? htmlspecialchars(trim($_POST['sender_name'])) : 'Anonymous';
    $clientEmail   = isset($_POST['sender_email']) ? filter_var(trim($_POST['sender_email']), FILTER_VALIDATE_EMAIL) : false;
    $clientSubject = isset($_POST['email_subject']) ? htmlspecialchars(trim($_POST['email_subject'])) : 'No Subject';
    $clientMessage = isset($_POST['email_message']) ? htmlspecialchars(trim($_POST['email_message'])) : '';

    // Enforce basic validation boundaries
    if (!$clientEmail) {
        $statusMessage = "<span style='color:red;'>Error: Please provide a valid email address.</span>";
    } elseif (empty($clientMessage)) {
        $statusMessage = "<span style='color:red;'>Error: Message content cannot be left empty.</span>";
    } else {
        $mail = new PHPMailer(true);

        try {
            // --- SERVER SETTINGS ---
            $mail->SMTPDebug = SMTP::DEBUG_OFF; // Change to SMTP::DEBUG_SERVER for deployment troubleshooting logs
            $mail->isSMTP();
            
            // --- SMTP PROVIDER PROFILES (Swap details below using section 2 instructions) ---
            $mail->Host       = 'smtp.sendgrid.net';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'apikey';
            $mail->Password   = 'SG.exampleKey';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = 587;

            // --- RECIPIENTS ---
            // Set your domain's verified email account as the sending agent
            $mail->setFrom('verified_sender@yourdomain.com', 'Web Contact Form');
            // Set where you want to receive the completed web submissions
            $mail->addAddress('admin@yourdomain.com', 'System Administrator');
            // Set the reply-to address to the user who filled out the form
            $mail->addReplyTo($clientEmail, $clientName);

            // --- CONTENT CREATION & VARIABLE PARSING ---
            $mail->isHTML(true);
            $mail->Subject = "New Form Submission: " . $clientSubject;
            
            // Construct structured HTML email content mapping our parsed data variables
            $mail->Body    = "
            <h3>New Message Summary</h3>
            <hr>
            <p><strong>Sender Name:</strong> {$clientName}</p>
            <p><strong>Sender Email:</strong> {$clientEmail}</p>
            <p><strong>Subject:</strong> {$clientSubject}</p>
            <p><strong>Message Content:</strong><br>" . nl2br($clientMessage) . "</p>";
            
            // Text fallback payload for older text-only client viewers
            $mail->AltBody = "Sender Name: {$clientName}\nSender Email: {$clientEmail}\nSubject: {$clientSubject}\nMessage:\n{$clientMessage}";

            $mail->send();
            $statusMessage = "<span style='color:green;'>Thank you! Your inquiry was delivered successfully.</span>";
        } catch (Exception $e) {
            $statusMessage = "<span style='color:red;'>System delivery failed. Engine Message: {$mail->ErrorInfo}</span>";
        }
    }
}
?>

<!-- Front-End Interaction View Component -->
<div style="background:#fdfdfd; padding:25px; border:1px solid #ddd; border-radius:5px; margin-top:20px;">
    <h3>Web Communication Portal</h3>
    
    <?php if(!empty($statusMessage)): ?>
        <div style="margin-bottom: 20px; font-weight: bold;"><?php echo $statusMessage; ?></div>
    <?php endif; ?>

    <form action="" method="POST" style="display: flex; flex-direction: column; gap: 15px; max-width: 500px;">
        <div>
            <label style="display:block; margin-bottom:5px;">Full Name</label>
            <input type="text" name="sender_name" required style="width:100%; padding:8px; box-sizing:border-box;">
        </div>
        
        <div>
<div><label style="display: block; margin-bottom: 5px;">Subject</label><input style="width: 100%; padding: 8px; box-sizing: border-box;" name="email_subject" required="" type="text" /></div>
<div><label style="display: block; margin-bottom: 5px;">Message Details</label><textarea style="width: 100%; padding: 8px; box-sizing: border-box;" name="email_message" required="" rows="5"></textarea></div>
<pre><button style="background: #1a73e8; color: white; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer; font-weight: bold;" type="submit">Send Secure Message</button>

Was this answer helpful?

« Back