PHP code example of postalsys / emailengine-php
1. Go to this page and download the library: Download postalsys/emailengine-php library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
postalsys / emailengine-php example snippets
use Postalsys\EmailEnginePhp\EmailEngine;
$client = new EmailEngine(
accessToken: 'your-access-token',
baseUrl: 'http://localhost:3000',
);
// List all accounts
$accounts = $client->accounts->list();
// Send an email
$result = $client->messages->submit('account-id', [
'from' => ['name' => 'Sender', 'address' => '[email protected] '],
'to' => [['name' => 'Recipient', 'address' => '[email protected] ']],
'subject' => 'Hello from EmailEngine PHP SDK',
'text' => 'This is a test email.',
'html' => '<p>This is a test email.</p>',
]);
$client = new EmailEngine(
accessToken: 'your-access-token', // Required: API access token
baseUrl: 'http://localhost:3000', // EmailEngine base URL (default: localhost:3000)
serviceSecret: 'your-service-secret', // For verifying webhook signatures
redirectUrl: 'http://your-app/callback', // Default redirect URL for hosted auth
timeout: 30, // Request timeout in seconds
);
$client = EmailEngine::fromOptions([
'access_token' => 'your-access-token',
'ee_base_url' => 'http://localhost:3000',
'service_secret' => 'your-service-secret',
'redirect_url' => 'http://your-app/callback',
]);
// Create a new account
$account = $client->accounts->create([
'account' => 'my-account',
'name' => 'John Doe',
'email' => '[email protected] ',
'imap' => [
'host' => 'imap.example.com',
'port' => 993,
'secure' => true,
'auth' => ['user' => '[email protected] ', 'pass' => 'password'],
],
'smtp' => [
'host' => 'smtp.example.com',
'port' => 465,
'secure' => true,
'auth' => ['user' => '[email protected] ', 'pass' => 'password'],
],
]);
// Get account info
$info = $client->accounts->get('my-account');
echo "Account state: " . $info['state'];
// List all accounts
$accounts = $client->accounts->list(['page' => 0, 'pageSize' => 20]);
// Force reconnection
$client->accounts->reconnect('my-account');
// Delete account
$client->accounts->delete('my-account');
// List messages in INBOX
$messages = $client->messages->list('my-account', [
'path' => 'INBOX',
'pageSize' => 50,
]);
// Get message details
$message = $client->messages->get('my-account', 'message-id', [
'textType' => 'html',
]);
// Search messages
$results = $client->messages->search('my-account', [
'path' => 'INBOX',
'search' => [
'unseen' => true,
'from' => '[email protected] ',
],
]);
// Update message flags
$client->messages->update('my-account', 'message-id', [
'flags' => ['add' => ['\\Seen', '\\Flagged']],
]);
// Move message
$client->messages->move('my-account', 'message-id', 'Archive');
// Delete message
$client->messages->delete('my-account', 'message-id');
// Bulk operations
$client->messages->bulkUpdate('my-account', [
'path' => 'INBOX',
'messages' => ['msg-1', 'msg-2', 'msg-3'],
'flags' => ['add' => ['\\Seen']],
]);
// Basic email
$result = $client->messages->submit('my-account', [
'from' => ['name' => 'Sender', 'address' => '[email protected] '],
'to' => [['name' => 'Recipient', 'address' => '[email protected] ']],
'cc' => [['address' => '[email protected] ']],
'subject' => 'Test Subject',
'text' => 'Plain text content',
'html' => '<p>HTML content</p>',
]);
// With attachments
$result = $client->messages->submit('my-account', [
'from' => ['address' => '[email protected] '],
'to' => [['address' => '[email protected] ']],
'subject' => 'Email with attachment',
'text' => 'Please see attached.',
'attachments' => [
[
'filename' => 'document.pdf',
'content' => base64_encode(file_get_contents('document.pdf')),
'contentType' => 'application/pdf',
],
],
]);
// Using templates
$result = $client->messages->submit('my-account', [
'to' => [['name' => 'John', 'address' => '[email protected] ']],
'template' => 'welcome-email',
'render' => [
'name' => 'John',
'company' => 'Acme Inc',
],
]);
// With idempotency key (prevents duplicates)
$result = $client->messages->submit('my-account', [
'to' => [['address' => '[email protected] ']],
'subject' => 'Important email',
'text' => 'Content',
], [
'idempotencyKey' => 'unique-key-12345',
]);
// Scheduled send
$result = $client->messages->submit('my-account', [
'to' => [['address' => '[email protected] ']],
'subject' => 'Scheduled email',
'text' => 'This will be sent later',
'sendAt' => '2024-12-25T10:00:00Z',
]);
// Download and stream an attachment directly to the browser
$client->download("/v1/account/my-account/attachment/AAAAAQAABRQ");
// List mailboxes
$mailboxes = $client->mailboxes->list('my-account', ['counters' => true]);
// Create mailbox
$client->mailboxes->create('my-account', 'INBOX/Projects');
// Rename mailbox
$client->mailboxes->rename('my-account', 'INBOX/OldName', 'INBOX/NewName');
// Delete mailbox
$client->mailboxes->delete('my-account', 'INBOX/ToDelete');
// Subscribe/unsubscribe
$client->mailboxes->subscribe('my-account', 'Archive');
$client->mailboxes->unsubscribe('my-account', 'Spam');
// Get webhook settings
$webhooks = $client->settings->getWebhooks();
// Configure webhooks
$client->settings->setWebhooks([
'enabled' => true,
'url' => 'https://your-app.com/webhooks',
'events' => ['messageNew', 'messageUpdated', 'messageSent'],
'headers' => ['Received', 'List-ID'],
'text' => 2048, // Include first 2KB of text content
]);
$client = new EmailEngine(
accessToken: 'your-token',
baseUrl: 'http://localhost:3000',
redirectUrl: 'http://your-app/auth-callback',
);
// Generate auth URL with basic options
$authUrl = $client->getAuthenticationUrl([
'account' => null, // null = auto-generate account ID
'name' => 'User Name',
'email' => '[email protected] ',
]);
// Redirect user to $authUrl
header('Location: ' . $authUrl);
// Example with all parameters
$authUrl = $client->getAuthenticationUrl([
'account' => 'user-123',
'name' => 'John Doe',
'email' => '[email protected] ',
'type' => 'gmail',
'delegated' => true,
'syncFrom' => '2024-01-01T00:00:00Z',
'notifyFrom' => '2024-01-01T00:00:00Z',
'subconnections' => ['Shared Mailbox'],
'path' => ['INBOX', 'Sent'],
]);
$client = new EmailEngine(
accessToken: 'your-token',
baseUrl: 'http://localhost:3000',
serviceSecret: 'your-service-secret',
);
// Get the raw request body and signature header
$body = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_EE_WH_SIGNATURE'] ?? '';
if ($client->verifyWebhookSignature($body, $signature)) {
// Signature is valid - process the webhook
$payload = json_decode($body, true);
// ... handle webhook event
} else {
// Invalid signature - reject the request
http_response_code(401);
exit('Invalid signature');
}
// List queued messages
$queue = $client->outbox->list(['account' => 'my-account']);
// Get queued message details
$item = $client->outbox->get('queue-id');
// Cancel scheduled message
$client->outbox->cancel('queue-id');
// Get system stats
$stats = $client->stats->get();
echo "EmailEngine version: " . $stats['version'];
echo "Connected accounts: " . $stats['connections']['connected'];
// Auto-discover email settings
$config = $client->stats->autoconfig('[email protected] ');
use Postalsys\EmailEnginePhp\Exceptions\AuthenticationException;
use Postalsys\EmailEnginePhp\Exceptions\AuthorizationException;
use Postalsys\EmailEnginePhp\Exceptions\NotFoundException;
use Postalsys\EmailEnginePhp\Exceptions\ValidationException;
use Postalsys\EmailEnginePhp\Exceptions\RateLimitException;
use Postalsys\EmailEnginePhp\Exceptions\ServerException;
use Postalsys\EmailEnginePhp\Exceptions\EmailEngineException;
try {
$account = $client->accounts->get('unknown-account');
} catch (NotFoundException $e) {
echo "Account not found: " . $e->getMessage();
echo "Error code: " . $e->getErrorCode();
} catch (AuthenticationException $e) {
echo "Invalid API token";
} catch (ValidationException $e) {
echo "Validation error: " . $e->getMessage();
print_r($e->getDetails());
} catch (RateLimitException $e) {
echo "Rate limited. Retry after: " . $e->getRetryAfter() . " seconds";
} catch (EmailEngineException $e) {
echo "API error: " . $e->getMessage();
}
// GET request
$response = $client->request('GET', '/v1/some-endpoint', query: ['param' => 'value']);
// POST request
$response = $client->request('POST', '/v1/some-endpoint', data: ['key' => 'value']);
// With custom headers
$response = $client->request('POST', '/v1/some-endpoint',
data: ['key' => 'value'],
headers: ['X-Custom-Header' => 'value']
);
// Old way (still works, but deprecated)
use EmailEnginePhp\EmailEngine;
$ee = new EmailEngine([
'access_token' => 'token',
'ee_base_url' => 'http://localhost:3000',
'service_secret' => 'secret',
'redirect_url' => 'http://callback.url',
]);
$ee->get_webhook_settings();
$ee->set_webhook_settings(['enabled' => true]);
$ee->get_authentication_url(['account' => null]);
bash
composer