reikem / mail-client
PHP client for the RKMail email API: send single, list and personalized batch mails, query history and download files.
Requires
- php: ^8.0
- ext-curl: *
Requires (Dev)
None
Suggests
- ext-fileinfo: Detects attachment MIME types; falls back to application/octet-stream.
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-01 09:58:42 UTC
README
PHP client for the RKMail email API. It submits mails over multipart/form-data, preserves every API response field and adds the HTTP status code. A WordPress plugin that routes wp_mail() through the same client is maintained in this repository and attached as a ZIP to every release.
Features
- Single mails, recipient lists and personalized batches in one request
- Attachments, scheduled delivery, Reply-To and CC
- Optional AI filter context that describes the expected scenario
- Mail history with status, rejection reasons and AI review metadata
- Download of inbound and outbound attachments
- Strict local validation before any HTTP request; no redirects and no automatic retries
- WordPress plugin for site-wide mail routing
Requirements
- PHP 8.0 to 8.6
ext-curl- Optional:
ext-fileinfofor MIME type detection (falls back toapplication/octet-stream) - An RKMail API endpoint with an auth key and an adapter key
Installation
composer require reikem/mail-client
Without Composer, require the files directly:
require_once __DIR__ . '/src/DTO/EmailAttachment.php'; require_once __DIR__ . '/src/EmailAPIClient.php'; require_once __DIR__ . '/src/MailStatus.php';
Quick start
Keep the credentials in protected server-side configuration, never in the browser or in version control:
// config/mailapi.php return [ 'api_url' => 'https://mail.example.com/api/send', 'auth_key' => 'YOUR_AUTH_KEY', 'adapter_key' => 'YOUR_ADAPTER_KEY', ];
require_once __DIR__ . '/vendor/autoload.php'; use Reikem\RKMail_Client\EmailAPIClient; $config = require __DIR__ . '/config/mailapi.php'; $client = new EmailAPIClient( apiUrl: $config['api_url'], authKey: $config['auth_key'], adapterKey: $config['adapter_key'], connectTimeout: 10, requestTimeout: 30 ); // Escape visitor input before placing it into an HTML template. $message = htmlspecialchars('I would like to sell my used PC.', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); $result = $client->sendMail( recipientEmail: 'sales@example.com', recipientName: 'Sales', regard: 'New purchase request', content: '<p>' . $message . '</p>', filterContext: 'Contact form for PC purchases. Hardware details and price expectations are expected.' ); foreach ($result['data']['statuses'] ?? [] as $entry) { // Store $entry['queueId'] and $entry['status'] in your application. }
content is the complete mail body. The client neither strips HTML nor shortens text. Both timeouts are positive seconds; requestTimeout bounds the whole request. TLS verification stays enabled.
API overview
| Method | Purpose |
|---|---|
sendMail($recipientEmail, $recipientName, $regard, $content, $attachments = [], $delayUntil = null, $filterContext = null, $replyTo = [], $cc = []) |
Send one mail |
sendMailList($recipients, $regard, $content, $attachments = [], $delayUntil = null, $filterContext = null, $replyTo = [], $cc = []) |
Send the same mail to an email => name|null map; the API stores one queue entry per recipient |
sendPersonalizedMailBatch($messages, $attachments = [], $filterContext = null, $replyTo = [], $cc = []) |
Send individual subjects and bodies in one request |
getMailHistory($dateFrom = null, $dateTo = null, $messageIds = null) |
Query outbound and inbound history by date and/or queue IDs |
downloadFile($source, $fileId, $targetPath = null) |
Download an inbound or outbound attachment |
createAttachments(array $paths) |
Build EmailAttachment objects from readable files |
All optional parameters are appended at the end, so positional calls written for earlier versions keep working.
Recipient lists, Reply-To and CC
$result = $client->sendMailList( recipients: ['service@example.com' => 'Service', 'office@example.com' => null], regard: 'New service request', content: '<p>Please call me back.</p>', replyTo: ['support@example.com' => 'Customer service'], cc: ['team@example.com', 'archive@example.com'] );
replyTois anemail => name|nullmap with up to 10 entries.ccis a zero-indexed list of up to 100 email strings. Addresses are trimmed, lowercased and deduplicated in order.- The shared CC list applies to every generated mail, so CC recipients can receive several copies.
Personalized batch
$result = $client->sendPersonalizedMailBatch( messages: [ [ 'recipient' => 'alice@example.com', 'recipient_name' => 'Alice', 'regard' => 'We received your request', 'content' => '<p>We will send you an offer.</p>', // No own context: inherits the shared filterContext. ], [ 'email' => 'bob@example.com', 'subject' => 'Your invoice', 'html' => '<p>Your invoice is available in your customer account.</p>', 'delayUntil' => time() + 3600, 'filter_context' => 'Invoice notification for an existing order.', ], ], filterContext: 'Automated notifications to existing customers.' ); foreach ($result['data']['results'] ?? [] as $entry) { // $entry['index'] maps to the zero-based input order. }
The whole batch is validated before the request. The server may still accept a valid batch partially.
Attachments and scheduling
$attachments = $client->createAttachments([__DIR__ . '/documents/invoice.pdf']); $client->sendMail( recipientEmail: 'customer@example.com', recipientName: null, regard: 'Your invoice', content: '<p>Please find your invoice attached.</p>', attachments: $attachments, delayUntil: new DateTimeImmutable('+1 hour') );
delayUntil accepts a DateTimeInterface or a positive Unix timestamp.
History and status
use Reikem\RKMail_Client\MailStatus; $history = $client->getMailHistory(messageIds: $queueIds); foreach ($history['data']['history']['Outbound'] ?? [] as $mail) { $status = $mail['status'] ?? null; $aiReason = $mail['filterDetails']['ai']['result']['reason'] ?? null; if ($status === MailStatus::REVIEW || $status === MailStatus::REJECTED) { // Inform an operator; do not resubmit automatically. } }
MailStatus provides FILTERING, QUEUED, REVIEW, REJECTED, SENT, FAILED, PREPARING and SENDING. Unknown future status values must not be treated as approval.
Downloads
$download = $client->downloadFile(source: 'outbound', fileId: 123); $saved = $client->downloadFile(source: 'inbound', fileId: 456, targetPath: __DIR__ . '/downloads');
The file ID comes from the attachment metadata in the history, not from queueId.
The API reference documents validation rules, response shapes, history fields and the AI filter context in detail.
Responses and errors
- Every method returns the decoded API envelope (
status,data, …) plushttpCode. - HTTP 200 with
data.success = truemeans at least one mail was accepted, not delivered. - HTTP 400 can contain stored, rejected mails with valid IDs. Always evaluate
data, not only the status code. - Valid API error responses are returned, not thrown.
InvalidArgumentException: invalid input such as recipients, IDs, context, CC/Reply-To or timeouts.RuntimeException: unreadable attachments, cURL errors and timeouts, invalid JSON envelopes or failed file writes. Messages never contain raw server responses.
There are no automatic retries or redirects. A timeout can happen after the API has stored the mail; check the history before resending.
Development
composer test # client integration suite composer test:wordpress # builds the WordPress plugin and runs its tests
The suites start a local PHP fixture server only. They need ext-curl, proc_open and loopback sockets; the WordPress build also needs ext-zip. No credentials, database, SMTP server or AI service is used, and no real mail is sent.
Pull requests run the test matrix for PHP 8.0 to 8.6. Releases are published from GitHub releases; see Releasing.
Releasing
Start a release in one of two ways:
- Run workflow: open the Release workflow, choose Run workflow on
main, and enter a new tag such asv1.2.0. The workflow tests the commit, builds the versioned WordPress ZIP and its checksum, publishes the GitHub release with generated notes, and starts the follow-up run on the tag (linked in the run summary). - GitHub release: create and publish a release for a new tag on
mainin the GitHub UI. The workflow attaches the WordPress ZIP and checksum to it.
In both cases the run on the tag tests it again, updates Packagist and verifies that Packagist lists the version for the tagged commit.
Tags such as v1.2.0-beta.1 must be published as pre-releases. To retry a failed publication or Packagist update, rerun the failed jobs from the corresponding workflow run.
Consumers then update with composer update reikem/mail-client.
Security
Please report vulnerabilities privately as described in SECURITY.md.
License
Released under the MIT License.