PHPMailer
PHPMailer is a full-featured, open-source email creation and transfer library for PHP, designed to simplify sending emails from web servers via protocols such as SMTP, while supporting advanced functionalities like attachments, HTML formatting, and UTF-8 encoding.[1]
Originally developed by Brent R. Matzelle in 2001 as a robust alternative to PHP's built-in mail() function, it has been actively maintained by Marcus Bointon (Synchromedia) and Andy Prevost since 2004, evolving from its initial hosting on SourceForge to the current GitHub repository established in 2013.[1]
Distributed under the GNU Lesser General Public License (LGPL) version 2.1 with a GPL Cooperation Commitment, PHPMailer is licensed to ensure broad compatibility with both open-source and proprietary projects.[1]
Key features include integrated SMTP support with authentication methods such as LOGIN, PLAIN, CRAM-MD5, and XOAUTH2; secure signing via DKIM and S/MIME; multi-part and alternative email formats; embedded images; and error messages in over 50 languages.[1]
It is compatible with PHP versions 5.5 through 8.4, installable primarily via Composer as the phpmailer/phpmailer package, and has garnered widespread adoption, with over 90 million total downloads and integration into major content management systems like WordPress, Drupal, and Joomla!.[2][1]
As of October 2025, the latest stable release is version 7.0.0, reflecting ongoing updates for security and PHP compatibility.[2]
Overview
Description
PHPMailer is an open-source PHP class library that provides a full-featured solution for creating and sending emails, supporting transport methods such as SMTP, sendmail, and PHP's built-in mail() function.[1] It addresses the limitations of PHP's native mail() function, which lacks support for authentication and complex message formatting, by offering a robust API for email handling in server-side applications.[2]
The library's primary use cases include facilitating email dispatch in web applications, such as user notifications, password resets, and bulk messaging, while efficiently managing MIME types to construct complex messages with mixed content types.[1] Developers integrate it to streamline email operations without relying on external mail servers or additional software, making it suitable for environments ranging from shared hosting to dedicated servers.[2]
In terms of technical scope, PHPMailer supports essential features like SMTP authentication via protocols such as LOGIN, PLAIN, CRAM-MD5, and XOAUTH2, along with attachments, HTML-formatted emails, and embedded images, all without requiring dependencies beyond core PHP.[1] It has evolved from early PHP email constraints—where basic functions struggled with secure transmission and multimedia content—into a standalone, widely adopted tool originating in 2001 and actively maintained since.[1]
License and Compatibility
PHPMailer is released under the GNU Lesser General Public License version 2.1 (LGPL v2.1), which permits its use in both open-source and commercial projects while requiring that any distributed modifications to the library include the source code.[3] This licensing model also incorporates the GPL Cooperation Commitment, ensuring compatibility with the broader GNU ecosystem and encouraging contributions back to the project.[3] As a result, developers can integrate PHPMailer into proprietary applications without needing to open-source their entire codebase, provided the library's terms are followed.
The library is distributed free of charge, with no licensing fees for the core functionality, and can be obtained through several methods including Composer package management via the command composer require phpmailer/phpmailer, direct download as a ZIP archive from the official GitHub repository, or cloning the repository for version control.[1] Commercial support options, such as subscriptions through Tidelift, are available for enterprises seeking professional assistance, but the open-source version remains fully functional without cost.[1]
In terms of PHP compatibility, PHPMailer requires PHP version 5.5 or higher for its current 7.0 series, with full support extending to the latest releases including PHP 8.4 as of 2025.[1] A legacy branch (5.2-stable) supports older PHP versions from 5.0 to 7.0, though it is no longer actively maintained.[4] No mandatory external dependencies are required beyond PHP itself, though optional packages like league/oauth2-client can enhance features such as XOAUTH2 authentication for specific SMTP providers.[1]
PHPMailer exhibits broad platform compatibility, operating seamlessly on Unix-like systems (such as Linux and macOS) and Windows environments, without reliance on local mail servers due to its built-in SMTP client.[1] It has been tested and verified to work with major web servers including Apache and Nginx, making it suitable for diverse hosting setups in production environments.[1]
Features
Core Functionality
PHPMailer provides essential methods for composing email messages, enabling developers to specify key headers and content programmatically. The setFrom method sets the sender's email address and optional name, ensuring compliance with email standards. Recipients are added via addAddress for primary "To" fields, while addCC and addBCC handle carbon copy and blind carbon copy recipients, respectively, supporting multiple addresses per call. The Subject property defines the email subject line, and the Body property allows setting the main content, which can be plain text or HTML-formatted, with AltBody providing a plain-text alternative for non-HTML clients. These methods facilitate straightforward message assembly before transmission.[5]
For dispatching emails, PHPMailer supports multiple transport methods, including SMTP for direct server connections, sendmail, Qmail, and the native PHP mail() function. When using SMTP—activated via the isSMTP() method—developers configure the connection with the Host property for the server hostname (e.g., 'smtp.example.com'), the Port property for the appropriate port (commonly 587 for STARTTLS or 465 for SSL), and the Timeout property to set connection timeout in seconds, preventing indefinite hangs. TLS/SSL encryption is enabled through the SMTPSecure property, specifying 'tls' or 'ssl' to secure the session. Sendmail and Qmail are invoked via isSendmail() and isQmail(), respectively, leveraging system binaries, while the default Mail transport relies on PHP's built-in function, though SMTP is recommended for reliability. The library handles the underlying protocol negotiations automatically during the send process.[1][5]
PHPMailer manages MIME types and encoding to ensure proper message rendering across clients, automatically generating multipart messages when both text and HTML bodies are provided. It supports encodings such as UTF-8 for character sets via the CharSet property, and options like base64, quoted-printable, or 8bit for content via the Encoding property, preventing issues with special characters or binary data. For mixed content, the library constructs MIME multipart/alternative structures, embedding text and HTML parts seamlessly without manual intervention. This automated handling simplifies compliance with RFC standards for email formatting.[5]
Error handling in PHPMailer is robust, with built-in exception throwing enabled by instantiating the class with a boolean true parameter, allowing try-catch blocks to capture failures like connection errors or invalid configurations. Debugging is facilitated by the SMTPDebug property, which accepts levels from 0 (disabled) to 4 (full server communication output), providing verbose logs for troubleshooting SMTP interactions or message issues directly to stdout or error logs.[1][5]
Basic validation ensures message integrity, with the validateAddress method checking email addresses against RFC 5322 format rules to detect malformed inputs early. Message size limits are enforced indirectly through PHP's php.ini settings, such as upload_max_filesize and post_max_size, which PHPMailer respects during composition to avoid transmission failures. These mechanisms promote reliable email delivery without advanced security configurations.[5]
Security and Authentication
PHPMailer supports multiple SMTP authentication mechanisms to securely verify credentials with mail servers, including LOGIN, PLAIN, CRAM-MD5, and XOAUTH2.[1] The LOGIN and PLAIN methods transmit credentials in base64-encoded form, while CRAM-MD5 provides challenge-response authentication for enhanced security without sending passwords in plaintext. XOAUTH2, an OAuth 2.0-based extension, allows token-based authentication and requires the additional league/oauth2-client dependency along with service-specific adapters for providers like Gmail.[1]
To protect data in transit, PHPMailer implements encryption protocols such as STARTTLS for opportunistic TLS upgrades over standard SMTP connections and implicit TLS via SMTPS. STARTTLS is typically used on port 587 for email submission, enabling an initial unencrypted handshake followed by encryption, whereas SMTPS operates on port 465 with encryption enforced from the outset. These options ensure compliance with secure email transmission standards, mitigating risks like eavesdropping on SMTP traffic.[1]
Credential management in PHPMailer involves setting the username and password through class properties like $mail->Username and $mail->Password, which are then used during SMTP authentication. Developers are advised to avoid hardcoding these values in source code to prevent exposure in version control or error logs; instead, store them securely using environment variables or configuration files outside the web root. Exposure of plaintext credentials can lead to unauthorized access to SMTP servers, underscoring the need for such practices.[1][6]
Anti-spoofing measures include automatic validation of email addresses, particularly the From address, to ensure syntactic correctness and reduce the risk of forged sender identities. Additionally, PHPMailer allows customization of the HELO or EHLO hostname via the $mail->Hostname property, which defaults to the system's hostname but can be set to match the domain for better server compliance and to avoid rejection due to hostname mismatches. This helps prevent issues where mail servers flag suspicious greetings as potential spoofing attempts.[1][7]
PHPMailer mitigates vulnerabilities such as injection attacks by sanitizing inputs, stripping newlines from headers to block CRLF injection, and generating unique MIME boundaries for multipart messages. These boundaries encapsulate email parts securely, preventing attackers from injecting unauthorized content like additional headers or recipients through user-supplied data. Such protections are integral to the library's design, ensuring safe composition and transmission without relying on external validation.[1][5]
Advanced Capabilities
PHPMailer supports attaching files to emails through the addAttachment method, which accepts a file path and optional parameters for renaming, encoding, MIME type, and disposition. For instance, to attach a file, one can use $mail->addAttachment('/path/to/file.pdf', 'document.pdf');, allowing multiple calls for several attachments. Additionally, addStringAttachment enables attaching content from strings, such as dynamically generated data, with parameters for filename, encoding, and type: $mail->addStringAttachment($pdfContent, 'report.pdf', PHPMailer::ENCODING_BASE64, 'application/pdf');.[1]
For embedding images in HTML emails, PHPMailer uses Content-ID (CID) attachments via the addEmbeddedImage method, which adds an inline image referenceable by CID in the HTML body. An example is $mail->addEmbeddedImage('images/logo.png', 'logo', '', PHPMailer::ENCODING_BASE64, 'image/png');, followed by <img src="cid:logo" alt="Logo"> in the $mail->Body. This facilitates rich, visually consistent emails without external hosting dependencies.[1]
PHPMailer enables HTML-formatted emails by setting $mail->isHTML(true);, which configures the message to use HTML in the Body property while supporting multipart MIME structures. To ensure accessibility, the AltBody property provides a plain-text version: $mail->Body = '<h1>Hello</h1><p>World!</p>'; $mail->AltBody = 'Hello World!';. Custom headers, such as Reply-To or Return-Path, can be added via $mail->addReplyTo('[email protected]'); or $mail->addCustomHeader('Return-Path', '[email protected]');, enhancing deliverability and user interaction. As noted in core functionality, MIME encoding handles the multipart assembly.[1]
For email signing and verification, PHPMailer natively supports DKIM signing by configuring properties like $mail->DKIM_domain = 'example.com'; $mail->DKIM_private = 'private_key'; $mail->DKIM_selector = 'selector';, which automatically generates and adds the DKIM-Signature header during sending to authenticate the sender and reduce spam filtering. S/MIME signing is available through the sign method: $mail->sign('cert.pem', 'key.pem', 'password');, enabling digital signatures for integrity and non-repudiation using X.509 certificates. While OpenPGP integration requires external libraries like php-gnupg, PHPMailer focuses on built-in DKIM and S/MIME for common secure email needs.[1]
Bulk mailing in PHPMailer is optimized by reusing a single instance across sends while clearing addresses between iterations to avoid mixing recipients, as shown in the mailing list example: loop over addresses with $mail->addAddress($email);, send, then $mail->clearAddresses();. This approach supports batch sending to thousands of recipients efficiently. To prevent blacklisting, developers implement rate limiting externally, such as adding sleep(1); between sends or using queues, since PHPMailer lacks built-in throttling but integrates well with such systems.[8]
Custom extensions in PHPMailer include OAuth2 authentication via the OAuth class, requiring the league/oauth2-client library: $mail->AuthType = 'XOAUTH2'; $mail->setOAuth(new PHPMailer\PHPMailer\[OAuth](/page/OAuth)('google', $clientId, $clientSecret, $refreshToken));. For custom transports, the class can be extended to override the send method or use alternative mailers like sendmail. Internationalization is handled through $mail->setLanguage('fr'); for over 50 languages and full UTF-8 support via $mail->CharSet = 'UTF-8';, ensuring proper encoding for global content without additional plugins.[1]
Installation and Setup
System Requirements
PHPMailer requires a minimum PHP version of 5.5 to utilize its current 7.0 release, which provides essential modern features and security updates.[1] For optimal performance, security, and compatibility with contemporary PHP features such as improved error handling and type declarations, PHP 7.4 or later is recommended.[9] In server environments, PHPMailer necessitates access to an SMTP server or a local mail transfer agent (MTA) for email transmission, with outbound ports such as 25 (unencrypted SMTP), 587 (submission with STARTTLS), or 465 (SMTPS) required to be open and unblocked by firewalls or hosting providers.[10]
The library maintains a low resource footprint, typically around 100 KB in size for core files, allowing it to operate efficiently on standard shared hosting plans without significant memory demands.[11] It can handle email messages up to approximately 10 MB, including attachments, on typical hosting configurations with default PHP memory limits of 128 MB or higher, though larger payloads may require increased memory allocation to avoid exhaustion errors.[12] The OpenSSL extension is optional but necessary for TLS/SSL encryption in secure SMTP connections; core functionality remains available without it for unencrypted or local mail delivery.[10]
PHPMailer is compatible with various testing environments, including shared hosting, VPS, and dedicated servers that support PHP 5.5 or later.[1] On shared hosting, common pitfalls include provider-specific restrictions like blocked SMTP ports (e.g., on GoDaddy) or legacy PHP settings such as safe_mode in versions prior to 5.4, which could limit file inclusions or network access, though these are obsolete in modern PHP installations.[10] VPS and dedicated setups generally offer fewer constraints, enabling full SMTP and encryption capabilities without additional configuration hurdles.[10]
Installation Methods
PHPMailer can be installed in PHP projects through automated dependency management or manual processes, ensuring compatibility with PHP 5.5 and later versions.[1] The recommended approach utilizes Composer for seamless integration and automatic updates, while manual installation offers flexibility for environments without Composer.[1]
Composer Installation
The primary method for installing PHPMailer involves Composer, a dependency manager for PHP that handles autoloading and version constraints. To install, execute the following command in your project directory:
bash
composer require phpmailer/phpmailer
composer require phpmailer/phpmailer
This adds PHPMailer to your composer.json file (typically as "phpmailer/phpmailer": "^7.0" or the latest stable version) and generates a vendor directory containing the library and an autoloader file at vendor/autoload.php.[1] For integration, include the autoloader in your PHP scripts with:
php
require 'vendor/autoload.php';
require 'vendor/autoload.php';
This enables automatic loading of PHPMailer classes without manual require statements.[1]
Manual Download
For projects without Composer, download the source directly from the official repository. Obtain the latest release as a ZIP archive from GitHub and extract it to a directory within your project's include path, such as includes/PHPMailer/.[1] Then, manually include the core files in your PHP script:
php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
The src directory contains the namespaced classes, and paths must be adjusted relative to your script's location.[1] This method requires explicit requires for each used class but avoids external dependencies.
Initial Setup
After installation, initial configuration involves loading the PHPMailer class and its SMTP subclass for transport handling. With Composer, the autoloader suffices; for manual setups, the requires listed above instantiate the classes via their namespaces. No further global configuration is needed at this stage, though project-specific paths should be verified to prevent loading errors.[1]
Verification
To confirm successful installation without attempting to send emails, create a simple test script that instantiates the PHPMailer object and checks for errors. For example:
php
<?php
require 'vendor/autoload.php'; // Or manual requires
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
echo "PHPMailer loaded successfully.";
<?php
require 'vendor/autoload.php'; // Or manual requires
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
echo "PHPMailer loaded successfully.";
Running this script outputs a success message if the classes load without exceptions, validating the setup.[1]
Upgrade Process
Upgrading PHPMailer typically occurs via Composer by running composer update phpmailer/phpmailer, which fetches the latest compatible version based on your composer.json constraints. For manual installations, download and replace the extracted files from the new release ZIP, ensuring the src directory structure is preserved. Migrations from version 5.2 to 6.x involve namespace adoption (PHPMailer\PHPMailer) and file relocation to src/. Upgrading from 6.x to 7.x requires attention to breaking changes, such as the lang(), setLanguage(), and $language properties now being static, which may affect child classes; always review changelogs for breaking changes.[1][13]
Usage
Basic Implementation
To implement PHPMailer for sending a simple text email, begin by instantiating the class with exceptions enabled, which allows for robust error handling through PHP's exception system. The constructor new PHPMailer(true) activates this mode, throwing a phpmailerException on failures instead of returning boolean values.[1]
For a basic text email, configure the transport using $mail->isMail() to leverage PHP's built-in mail() function, avoiding the need for SMTP setup in minimal scenarios. Set the sender with $mail->setFrom('[email protected]', 'Name'), add the recipient via $mail->addAddress('[email protected]', 'Name'), assign the subject with $mail->Subject = 'Subject Line', and define the plain-text body using $mail->Body = 'Message content'. Finally, invoke $mail->send() to dispatch the email.[1]
Wrap the configuration and send operation in a try-catch block to handle potential errors gracefully. In the catch clause, access $mail->ErrorInfo to retrieve a descriptive string of the failure, such as connection issues or invalid parameters, enabling targeted debugging.[1]
The following complete PHP code snippet demonstrates sending a basic account notification email, assuming PHPMailer is installed via Composer:
php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isMail();
$mail->setFrom('[email protected]', 'System');
$mail->addAddress('[email protected]', 'User');
$mail->Subject = 'Account Activation';
$mail->Body = 'Your account has been activated. Please log in to proceed.';
$mail->send();
echo 'Notification sent successfully.';
} catch (Exception $e) {
echo "Failed to send notification. Error: {$mail->ErrorInfo}";
}
?>
```[](https://github.com/PHPMailer/PHPMailer)
When reusing a PHPMailer instance for multiple emails, such as in batch notifications, a frequent oversight is neglecting to call `$mail->clearAddresses()` between sends, which appends new recipients to prior ones and risks exposing unintended email addresses.[](https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps)
### Configuration Options
PHPMailer provides a range of configuration options to customize its behavior for different email sending scenarios, allowing developers to adapt the library to specific server environments and application needs. These options are set as public properties on the PHPMailer instance and cover aspects such as SMTP server connections, message formatting, connection management, and debugging.[](https://github.com/PHPMailer/PHPMailer)
For SMTP-specific configurations, the **Host** property specifies the SMTP server address, defaulting to '[localhost](/page/Localhost)' for local mail transfer agents, while **Port** sets the connection port, with a default of 25 for unencrypted SMTP. Authentication is handled via **Username** and **Password**, both defaulting to empty strings, enabling secure login to external servers like [Gmail](/page/Gmail) or [Outlook](/page/Outlook). The **SMTPSecure** option controls [encryption](/page/Encryption), supporting values such as '' (none), 'tls' for [opportunistic encryption](/page/Opportunistic_encryption) on port 587, or 'ssl' for implicit [encryption](/page/Encryption) on port 465, with no default [encryption](/page/Encryption) applied. Additionally, **AuthType** allows selection of [authentication](/page/Authentication) mechanisms like '[LOGIN](/page/Login)', '[PLAIN](/page/Plain)', 'CRAM-MD5', or 'XOAUTH2', defaulting to an empty string which triggers automatic detection based on server capabilities.[](https://github.com/PHPMailer/PHPMailer)[](https://github.com/PHPMailer/PHPMailer/blob/master/src/PHPMailer.php)
Message customization options include **CharSet**, which defaults to UTF-8 to support international characters in modern applications, ensuring proper rendering of non-ASCII text. The **Encoding** property determines the content transfer encoding, defaulting to '8bit' but commonly set to 'base64' or 'quoted-printable' for better compatibility with [MIME](/page/MIME) standards, especially when handling attachments or [HTML](/page/HTML) content. **WordWrap** controls line wrapping in the message body, defaulting to 0 (disabled), but setting it to 76 or similar ensures compliance with [RFC](/page/RFC) 5322 for [email](/page/Email) readability.[](https://github.com/PHPMailer/PHPMailer)[](https://github.com/PHPMailer/PHPMailer/issues/765)
To manage connection reliability, **Timeout** sets the SMTP connection timeout in seconds, defaulting to 300 (5 minutes) as per RFC 2821 guidelines, preventing indefinite hangs during network issues. For batch sending, **SMTPKeepAlive** keeps the SMTP connection open after each message when set to true (default false), reducing overhead in loops for multiple recipients.[](https://github.com/PHPMailer/PHPMailer)[](https://github.com/PHPMailer/PHPMailer/blob/master/src/PHPMailer.php)
Logging and [debugging](/page/Debugging) are configured via **SMTPDebug**, which controls output verbosity with levels from 0 (off, default) to 4 (low-level data), and **Debugoutput**, defaulting to '[echo](/page/Echo)' but customizable to '[html](/page/HTML)', 'error_log', or a callback [function](/page/Function) for [logging](/page/Logging) to files or external systems. For example, to enable server-level [debugging](/page/Debugging) and [log](/page/Log) to a file:
```php
$mail->SMTPDebug = 2; // Server messages
$mail->Debugoutput = function($str, $level) {
error_log("Debug level $level; message: $str", 3, '/path/to/debug.log');
};
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->isMail();
$mail->setFrom('[email protected]', 'System');
$mail->addAddress('[email protected]', 'User');
$mail->Subject = 'Account Activation';
$mail->Body = 'Your account has been activated. Please log in to proceed.';
$mail->send();
echo 'Notification sent successfully.';
} catch (Exception $e) {
echo "Failed to send notification. Error: {$mail->ErrorInfo}";
}
?>
```[](https://github.com/PHPMailer/PHPMailer)
When reusing a PHPMailer instance for multiple emails, such as in batch notifications, a frequent oversight is neglecting to call `$mail->clearAddresses()` between sends, which appends new recipients to prior ones and risks exposing unintended email addresses.[](https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps)
### Configuration Options
PHPMailer provides a range of configuration options to customize its behavior for different email sending scenarios, allowing developers to adapt the library to specific server environments and application needs. These options are set as public properties on the PHPMailer instance and cover aspects such as SMTP server connections, message formatting, connection management, and debugging.[](https://github.com/PHPMailer/PHPMailer)
For SMTP-specific configurations, the **Host** property specifies the SMTP server address, defaulting to '[localhost](/page/Localhost)' for local mail transfer agents, while **Port** sets the connection port, with a default of 25 for unencrypted SMTP. Authentication is handled via **Username** and **Password**, both defaulting to empty strings, enabling secure login to external servers like [Gmail](/page/Gmail) or [Outlook](/page/Outlook). The **SMTPSecure** option controls [encryption](/page/Encryption), supporting values such as '' (none), 'tls' for [opportunistic encryption](/page/Opportunistic_encryption) on port 587, or 'ssl' for implicit [encryption](/page/Encryption) on port 465, with no default [encryption](/page/Encryption) applied. Additionally, **AuthType** allows selection of [authentication](/page/Authentication) mechanisms like '[LOGIN](/page/Login)', '[PLAIN](/page/Plain)', 'CRAM-MD5', or 'XOAUTH2', defaulting to an empty string which triggers automatic detection based on server capabilities.[](https://github.com/PHPMailer/PHPMailer)[](https://github.com/PHPMailer/PHPMailer/blob/master/src/PHPMailer.php)
Message customization options include **CharSet**, which defaults to UTF-8 to support international characters in modern applications, ensuring proper rendering of non-ASCII text. The **Encoding** property determines the content transfer encoding, defaulting to '8bit' but commonly set to 'base64' or 'quoted-printable' for better compatibility with [MIME](/page/MIME) standards, especially when handling attachments or [HTML](/page/HTML) content. **WordWrap** controls line wrapping in the message body, defaulting to 0 (disabled), but setting it to 76 or similar ensures compliance with [RFC](/page/RFC) 5322 for [email](/page/Email) readability.[](https://github.com/PHPMailer/PHPMailer)[](https://github.com/PHPMailer/PHPMailer/issues/765)
To manage connection reliability, **Timeout** sets the SMTP connection timeout in seconds, defaulting to 300 (5 minutes) as per RFC 2821 guidelines, preventing indefinite hangs during network issues. For batch sending, **SMTPKeepAlive** keeps the SMTP connection open after each message when set to true (default false), reducing overhead in loops for multiple recipients.[](https://github.com/PHPMailer/PHPMailer)[](https://github.com/PHPMailer/PHPMailer/blob/master/src/PHPMailer.php)
Logging and [debugging](/page/Debugging) are configured via **SMTPDebug**, which controls output verbosity with levels from 0 (off, default) to 4 (low-level data), and **Debugoutput**, defaulting to '[echo](/page/Echo)' but customizable to '[html](/page/HTML)', 'error_log', or a callback [function](/page/Function) for [logging](/page/Logging) to files or external systems. For example, to enable server-level [debugging](/page/Debugging) and [log](/page/Log) to a file:
```php
$mail->SMTPDebug = 2; // Server messages
$mail->Debugoutput = function($str, $level) {
error_log("Debug level $level; message: $str", 3, '/path/to/debug.log');
};
This setup aids in troubleshooting connection or authentication errors.[1][14]
PHPMailer supports HTML messages with embedded CSS by setting the isHTML property to true, allowing inline styles directly in the body content for self-contained emails. Custom validation rules for addresses can be applied using the static validateAddress method with modes like 'php' (default filter_var), 'html5', or 'pcre' for stricter regex checks, enhancing security against invalid inputs. An example configuration for an HTML email with embedded CSS and custom validation:
php
$mail->isHTML(true);
$mail->Body = '<html><head><style>body { font-family: Arial; color: [blue](/page/Blue); }</style></head><body><h1>Hello</h1></body></html>';
if (!PHPMailer::validateAddress('[email protected]', '[html5](/page/HTML5)')) {
echo 'Invalid [email address](/page/Email_address)';
}
$mail->isHTML(true);
$mail->Body = '<html><head><style>body { font-family: Arial; color: [blue](/page/Blue); }</style></head><body><h1>Hello</h1></body></html>';
if (!PHPMailer::validateAddress('[email protected]', '[html5](/page/HTML5)')) {
echo 'Invalid [email address](/page/Email_address)';
}
These tweaks enable tailored, secure email handling without relying on external stylesheets.[1][15]
History
Development Origins
PHPMailer was developed by Brent R. Matzelle in 2001 as a standalone PHP class to overcome the limitations of PHP's native [mail](/page/Mail)() function, which primarily supported plain-text messages and lacked built-in capabilities for attachments, HTML formatting, or direct SMTP integration.[16][1] The project emerged during a period of rapid expansion in web applications, where developers required a reliable, portable solution for email delivery without relying on external frameworks like PEAR, ensuring compatibility across diverse hosting environments without additional dependencies.[16][17]
The initial goals focused on providing comprehensive email transport features, including support for multiple file attachments, CCs, BCCs, redundant SMTP servers, and word wrapping, while allowing sends via sendmail, QMail, or direct SMTP protocols.[16] Version 1.0 was released the same year and hosted on SourceForge, marking PHPMailer's debut as an open-source tool aimed at simplifying email handling for PHP developers.[1][16]
Early maintenance saw contributions from the community, with a notable transition around 2004 when Marcus Bointon (known as coolbru on SourceForge and associated with Synchromedia) became a key maintainer alongside Brent R. Matzelle, helping to sustain the project's growth amid increasing demand for robust email functionality in web development.[1][17] This shift laid the groundwork for ongoing enhancements while preserving the library's lightweight design.
Key Releases and Updates
PHPMailer underwent significant evolution starting with version 5.0, released in 2008, which marked a major refactor toward object-oriented programming (OOP) principles, enhancing modularity and extensibility for email handling in PHP applications.[2] This version laid the groundwork for modern usage by introducing class-based structures that improved code organization and reduced reliance on procedural scripts.[16]
A pivotal milestone arrived with version 6.0 in 2016, which adopted PSR-4 autoloading standards, added full support for PHP 7, and introduced namespaces under PHPMailer\PHPMailer to align with contemporary PHP practices.[2] These changes enabled seamless integration with Composer dependency management, boosting compatibility with modern frameworks and reducing setup complexity.
In 2010, the project became an Apache incubator on Google Code, and in 2013, it migrated to its current GitHub repository.[1]
Recent updates in the v6.8 series and beyond, spanning 2023 to 2025, have focused on refining OAuth2 authentication mechanisms, including better handling of long access tokens and integration with libraries like league/oauth2-client for secure token management.[18] Security enhancements in these releases addressed potential vulnerabilities, such as XSS risks from malformed DSN parsing in v6.8.0 and patches for known CVEs, including object injection issues reported in earlier sub-versions.[9] By v6.9.3, released on November 24, 2024, support extended to PHP 8.4 with experimental PHP 8.5 compatibility, ensuring ongoing robustness against emerging threats. Additionally, v7.0.0, released on October 15, 2025, introduced breaking changes for child class extensions while incorporating static language methods for improved internationalization.[2]
Key breaking changes across updates include the shift from the legacy PHPMailerAutoload.php to Composer-based autoloading in v6.0, which eliminated manual includes but required reconfiguration for non-Composer environments.[13] Deprecated transports, such as the pipe transport, were fully removed in subsequent versions to streamline code and enhance security by focusing on supported protocols like SMTP and sendmail.[13]
Maintenance of PHPMailer remains active through its GitHub repository, which has amassed over 21,900 stars as of late 2025, reflecting strong community engagement.[1] The project undergoes regular security audits, with 19 advisories published and a dedicated policy for private vulnerability reporting to mitigate risks promptly.[19] PHP compatibility updates are prioritized, with continuous integration ensuring support from PHP 5.5 through the latest versions, including deprecation handling for legacy features.[1]
Adoption
Popularity Metrics
PHPMailer has achieved substantial adoption in the PHP ecosystem, primarily through its availability as a Composer package and integration into major open-source projects. As of October 2025, it has surpassed 90 million total downloads on Packagist, positioning it among the most widely installed PHP libraries for email functionality.[2]
The project's GitHub repository demonstrates robust community involvement, with 33 open issues and 13 active pull requests as of November 2025, alongside frequent releases that ensure compatibility with the latest PHP versions up to 8.4.[1][9]
PHPMailer is consistently recognized as a leading PHP email library in developer resources and compilations, appearing in curated lists of top libraries for web development in 2025 due to its reliability and feature set.[20][21]
Its presence extends to high-profile content management systems, including WordPress, Drupal, Joomla, and others, where it powers email features and contributes to its deployment across millions of websites worldwide.[1]
The library receives endorsements in established technical literature, such as O'Reilly's "Pro PHP Programming," which highlights its utility for email and SMS message generation, and similar references in WordPress development guides.[22][23]
Community and Alternatives
PHPMailer benefits from an active open-source community, with support primarily channeled through its official GitHub repository, where users report bugs and request features via the issues tracker.[24] Additionally, the project maintains a dedicated tag on Stack Overflow for user questions and troubleshooting, fostering collaborative problem-solving among developers.[25] Comprehensive official documentation, including setup guides and API references, is hosted on the project's wiki and dedicated site, while a dedicated examples directory in the repository provides practical code snippets for common use cases.[26][27][15]
In July 2025, the U.S. Cybersecurity and Infrastructure Security Agency (CISA) added CVE-2016-10033, a remote code execution vulnerability in PHPMailer versions prior to 5.2.18, to its Known Exploited Vulnerabilities catalog due to observed active exploitation.[28]
Contributions to PHPMailer are encouraged through pull requests on GitHub, with the project welcoming improvements, bug fixes, and new features from the community.[1] Developers are guided to first discuss proposed changes via issues to ensure alignment with project standards, and the repository includes contribution guidelines emphasizing code quality, testing, and compatibility with supported PHP versions.
As a standalone library, PHPMailer offers advantages over alternatives like Symfony Mailer, the successor to SwiftMailer, which reached end-of-maintenance in November 2021, providing enhanced framework-specific features—and Laminas\Mail, the successor to Zend\Mail, by providing simplicity and independence from any PHP framework.[29] Unlike the native PHP mail() function, which lacks robust error handling and transport options, PHPMailer supports multiple protocols such as SMTP and IMAP without requiring external dependencies. These attributes make it particularly suitable for lightweight applications or environments avoiding framework overhead.
Migration from older versions, such as PHPMailer v5 to v6, is facilitated by clear upgrade documentation that addresses key changes like the introduction of namespaces (e.g., PHPMailer\PHPMailer) and relocation of source files to a src/ directory, allowing most codebases to transition with minimal adjustments.[30]
PHPMailer integrates seamlessly into popular PHP frameworks, with community-maintained plugins and wrappers available for Laravel and Symfony to handle email transport within their ecosystems.[31] It is also commonly employed in CI/CD pipelines for automated email testing, often paired with SMTP mock servers to verify message delivery without sending real emails.[32]