Sockets-based library for sending HTML email messages.
- Motivation
- Supported PHP Versions
- Installation
- Quick Start
- Usage
- Examples
- Testing
- Contributing
- License
- Support
- Changelog
Most mailing libraries treat the email body as a string you pass in. WebFiori Mailer treats emails as HTML documents you build using a virtual DOM. You compose emails the same way you'd build a web page — inserting elements, nesting children, setting styles programmatically:
$div = $email->insert('div');
$div->addChild('p')->text('Hello!');
$div->addChild('p', ['style' => ['color' => 'red']])->text('Important message.');No raw HTML strings. No template engine required (though templates are supported too).
The library relies only on two lightweight packages (webfiori/ui for DOM building and webfiori/file for attachments). The SMTP layer is built directly on PHP sockets. No heavy third-party dependencies to keep up with.
Testing emails shouldn't require actually sending them or setting up third-party services:
- Store mode — Renders the email as a local HTML file for visual inspection, complete with headers metadata.
- Test send mode — Redirects messages to specified test addresses regardless of the actual recipients.
Switch between modes with a single call:
$email->setMode(SendMode::TEST_STORE, ['store-path' => '/tmp/emails']);Every command sent to the SMTP server is logged with its response code and message. When something fails, you see exactly what happened at the protocol level — no black-box debugging.
The entire library is a handful of classes. If all you need is to send HTML emails over SMTP without pulling in a large framework or dozens of transitive dependencies, this gets the job done.
| Build Status |
|---|
composer require webfiori/mailer<?php
use WebFiori\Mail\AccountOption;
use WebFiori\Mail\SMTPAccount;
use WebFiori\Mail\Email;
$smtp = new SMTPAccount([
AccountOption::PORT => 465,
AccountOption::SERVER_ADDRESS => 'mail.example.com',
AccountOption::USERNAME => 'test@example.com',
AccountOption::PASSWORD => 'secret',
AccountOption::SENDER_NAME => 'My App',
AccountOption::SENDER_ADDRESS => 'test@example.com',
AccountOption::NAME => 'no-reply'
]);
$email = new Email($smtp);
$email->setSubject('Hello World From PHP 😀');
$email->addTo('recipient@example.com');
$div = $email->insert('div');
$div->addChild('p')->text('Hello World Message');
$div->addChild('p', ['style' => ['font-weight' => 'bold', 'color' => 'red']])
->text('This is just a test message.');
$email->send();Connection information is represented using an instance of the class WebFiori\Mail\SMTPAccount.
<?php
use WebFiori\Mail\SMTPAccount;
use WebFiori\Mail\AccountOption;
$smtp = new SMTPAccount([
AccountOption::PORT => 465,
AccountOption::SERVER_ADDRESS => 'mail.example.com',
AccountOption::USERNAME => 'test@example.com',
AccountOption::PASSWORD => 'KnvcbxFYCz77',
AccountOption::SENDER_NAME => 'Ibrahim',
AccountOption::SENDER_ADDRESS => 'test@example.com',
AccountOption::NAME => 'no-reply'
]);use WebFiori\Mail\Email;
$email = new Email($smtp);$email->setSubject('Hello World From PHP 😀');$email->addTo('recipient@example.com');The email messages are HTML based, utilizing the library webfiori/ui to build the virtual DOM.
$div = $email->insert('div');
$div->addChild('p')->text('Hello World Message');
$div->addChild('p', [
'style' => [
'font-weight' => 'bold',
'color' => 'red'
]
])->text('This is just a test message.');$email->send();WebFiori Mailer supports method chaining for a more readable and concise syntax:
$email = new Email($smtpAccount);
$email->to('recipient@example.com', 'Recipient Name')
->cc('manager@example.com', 'Manager')
->subject('Hello from WebFiori Mailer!')
->priority(1)
->send();Available fluent methods:
to()- Add TO recipientcc()- Add CC recipientbcc()- Add BCC recipientsubject()- Set email subjectattach()- Add attachmentpriority()- Set email priority
WebFiori Mailer supports OAuth2 authentication via the OAuthTokenProvider interface.
Built-in providers handle token acquisition, caching, and refresh automatically.
The token is fetched lazily — just before each send — so it is always fresh.
Uses the Client Credentials flow against Microsoft Entra ID. No user interaction required.
use WebFiori\Mail\MicrosoftOAuthProvider;
$provider = new MicrosoftOAuthProvider(
tenantId: getenv('SMTP_TENANT_ID'),
clientId: getenv('SMTP_CLIENT_ID'),
clientSecret: getenv('SMTP_CLIENT_SECRET')
);
$account = new SMTPAccount([
AccountOption::SERVER_ADDRESS => 'smtp.office365.com',
AccountOption::PORT => 587,
AccountOption::USERNAME => getenv('SMTP_USERNAME'),
AccountOption::SENDER_ADDRESS => getenv('SMTP_USERNAME'),
AccountOption::SENDER_NAME => 'My App',
]);
$account->setTokenProvider($provider);Implement OAuthTokenProvider for any other OAuth2-capable SMTP server:
use WebFiori\Mail\OAuthTokenProvider;
class MyProvider implements OAuthTokenProvider {
public function getToken(): string {
// fetch, cache, and return your access token
}
}
$account->setTokenProvider(new MyProvider());See the OAuth examples for complete setup instructions.
Amazon SES SMTP uses IAM credentials, not OAuth. SESCredentialHelper derives the
required SMTP password from your IAM Secret Access Key:
use WebFiori\Mail\SESCredentialHelper;
$region = 'us-east-1';
$account = new SMTPAccount([
AccountOption::SERVER_ADDRESS => SESCredentialHelper::smtpEndpoint($region),
AccountOption::PORT => 587,
AccountOption::USERNAME => getenv('AWS_ACCESS_KEY_ID'),
AccountOption::PASSWORD => SESCredentialHelper::deriveSmtpPassword(
getenv('AWS_SECRET_ACCESS_KEY'), $region
),
AccountOption::SENDER_ADDRESS => 'sender@verified-domain.com',
AccountOption::SENDER_NAME => 'My App',
]);No special transport needed — SES SMTP uses standard AUTH LOGIN.
See the SES example for full details.
By default, SSL/TLS peer verification is enabled for all connections. This means:
- The server certificate is verified against your system's CA bundle (
verify_peer = true) - The certificate hostname must match the server address (
verify_peer_name = true) - Self-signed certificates are rejected (
allow_self_signed = false)
This is the correct and secure default for any publicly trusted SMTP server.
$account = new SMTPAccount([
AccountOption::SERVER_ADDRESS => 'mail.internal.example.com',
AccountOption::PORT => 587,
AccountOption::USERNAME => 'no-reply@internal.example.com',
AccountOption::PASSWORD => 'secret',
AccountOption::SENDER_ADDRESS => 'no-reply@internal.example.com',
AccountOption::SENDER_NAME => 'Internal Mailer',
AccountOption::ALLOW_SELF_SIGNED => true, // allow self-signed cert; verify_peer stays on
]);$account = new SMTPAccount([
// ...
AccountOption::VERIFY_SSL => false, // disables verify_peer and verify_peer_name
]);Warning: Setting
VERIFY_SSLtofalseexposes SMTP credentials to man-in-the-middle attacks. Only use it in isolated/controlled environments.
See the SSL configuration example for a full demonstration.
Failed connections are automatically retried with exponential backoff. The read timeout applies to every fgets() call after the connection is established, preventing indefinite hangs when a server becomes unresponsive mid-session.
| Option | Default | Description |
|---|---|---|
AccountOption::MAX_RETRIES |
3 |
Number of reconnect attempts after failure |
AccountOption::RETRY_DELAY |
1 |
Base delay in seconds between attempts (doubles each retry) |
Backoff schedule with defaults: attempt 1 immediate, attempt 2 waits 1s, attempt 3 waits 2s, attempt 4 waits 4s.
$account = new SMTPAccount([
// ...
AccountOption::MAX_RETRIES => 5, // retry up to 5 times
AccountOption::RETRY_DELAY => 2, // backoff: 2s, 4s, 8s, 16s, 32s
]);
// Disable retries entirely:
$account->setMaxRetries(0);Note: Retries only apply to TCP connection establishment. A
SMTPExceptionthrown duringread()due to a timeout means the session state is unknown and cannot be safely retried in place — the caller should reconnect from scratch.
See ADR-0032 for the full design rationale.
Every sent email automatically gets a unique Message-ID header (RFC 5322). After calling send(), you can read it back:
$email->send();
echo $email->getMessageId(); // e.g. <a3f2...@smtp.gmail.com>To send a reply that threads correctly in email clients, set the In-Reply-To header:
$reply = new Email($account);
$reply->setInReplyTo($originalEmail->getMessageId());
$reply->setSubject('Re: Original Subject');
$reply->addTo('sender@example.com');
$reply->send();Attachments can be added using Email::addAttachment(). The parameter can be a file path string or an object of type webfiori\file\File.
use webfiori\file\File;
$email->addAttachment('Attach00.txt');
$email->addAttachment(new File('another.txt'));Execute logic before the message is sent using Email::addBeforeSend():
$email->addBeforeSend(function (Email $e) {
$e->insert('p')->text('This text is added before sending');
});Execute logic after the message is sent using Email::addAfterSend():
$email->addAfterSend(function (Email $e) {
// Do any action like storing the log.
});Every SMTP command is logged with its response code and message. Access log events via Email::getLog():
foreach ($email->getLog() as $logEvent) {
echo ' Command: '.$logEvent['command'];
echo ' Code: '.$logEvent['response-code'];
echo ' Message: '.$logEvent['response-message'];
}Emails can be stored as HTML web pages for preview purposes:
$email->storeEmail('/path/to/email/file');This will:
- Render the final email
- Create a folder named after the email subject
- Create an HTML file named with the current date and time
The library provides two testing modes controlled by Email::setMode():
$email->setMode(SendMode::TEST_STORE, [
'store-path' => '/path/to/store/message'
]);
$email->send(); // Stores instead of sending$email->setMode(SendMode::TEST_SEND, [
'send-addresses' => [
'addr1@example.com',
'addr2@example.com',
]
]);
$email->send(); // Sends to test addresses onlyComprehensive examples are available in the examples/ directory:
- Basic Usage - Fundamental email sending and fluent interface
- OAuth Authentication - Gmail and Microsoft OAuth integration
- File Attachments - Adding files to emails
- Sending Modes - Test, development, and production configurations
- SMTP Logging - Debugging and monitoring
- Callbacks - Before/after send custom logic
- Custom Transports - Connection reuse and pluggable transports
# Install dependencies
composer install
# Run tests
composer testContributions are welcome! Please open an issue or submit a pull request on GitHub.
This library is licensed under the MIT License. See the LICENSE file for more details.
If you encounter any issues, please open an issue on GitHub.
See CHANGELOG.md for a list of changes.
