Skip to main content

EmailEngine AI Agent Reference

This document is designed for AI coding assistants helping developers integrate with the EmailEngine API. It provides a consolidated, machine-parseable overview of all capabilities, endpoints, and patterns.

What EmailEngine Does

EmailEngine is a self-hosted email API gateway that provides REST API access to email accounts via:

  • IMAP/SMTP protocols
  • Gmail API (native)
  • Microsoft Graph API (native)
  • OAuth2 authentication

Key value proposition: Instead of dealing with IMAP/SMTP protocols directly, developers interact with a single REST API. EmailEngine handles connection management, authentication, synchronization, and real-time notifications via webhooks.

Quick Facts

AspectDetails
API StyleRESTful JSON
AuthenticationBearer token (Authorization: Bearer TOKEN)
Base URLhttp://localhost:3000/v1 (default)
WebhooksHTTP POST to configured endpoint
Data StorageRedis (credentials encrypted with EENGINE_SECRET)
Message StorageNone - fetched from mail server on demand
Admin AuthPassword + TOTP, passkeys (WebAuthn), Okta SSO

Core Capabilities Matrix

CapabilityEndpointKey Parameters
Register accountPOST /v1/accountaccount, imap, smtp, or oauth2
List accountsGET /v1/accountspage, pageSize, state
Get accountGET /v1/account/{account}-
Update accountPUT /v1/account/{account}Partial updates supported
Delete accountDELETE /v1/account/{account}-
Reconnect accountPUT /v1/account/{account}/reconnect-
Send emailPOST /v1/account/{account}/submitto, subject, text/html
List messagesGET /v1/account/{account}/messagespath, page, pageSize
Get messageGET /v1/account/{account}/message/{message}textType, embedAttachedImages
Search messagesPOST /v1/account/{account}/searchsearch object
Update messagePUT /v1/account/{account}/message/{message}flags, labels, seen
Delete messageDELETE /v1/account/{account}/message/{message}-
Move messagePUT /v1/account/{account}/message/{message}/movepath (destination)
Download attachmentGET /v1/account/{account}/attachment/{attachment}-
List mailboxesGET /v1/account/{account}/mailboxes-
Create mailboxPOST /v1/account/{account}/mailboxpath
Delete mailboxDELETE /v1/account/{account}/mailboxpath
Configure webhooksPOST /v1/settingswebhooks, webhookEvents
Manage templatesPOST /v1/templates/templatename, content, format
View outboxGET /v1/outbox-
Cancel queued emailDELETE /v1/outbox/{queueId}-
Generate auth formPOST /v1/authentication/formaccount, redirectUrl

Complete API Endpoints

Account Management

MethodEndpointDescription
POST/v1/accountRegister new email account
GET/v1/accountsList all accounts (paginated)
GET/v1/account/{account}Get account details and status
PUT/v1/account/{account}Update account configuration
DELETE/v1/account/{account}Delete account
PUT/v1/account/{account}/reconnectForce reconnection
PUT/v1/account/{account}/flushReset sync state, re-index
PUT/v1/account/{account}/syncTrigger immediate sync
GET/v1/account/{account}/oauth-tokenGet current OAuth2 access token
POST/v1/verifyAccountTest account credentials
POST/v1/authentication/formGenerate hosted auth form URL
GET/v1/autoconfigAuto-detect IMAP/SMTP settings
GET/v1/account/{account}/server-signaturesList server signatures for account

Message Operations

MethodEndpointDescription
GET/v1/account/{account}/messagesList messages in mailbox
GET/v1/account/{account}/message/{message}Get message details
GET/v1/account/{account}/message/{message}/sourceGet raw RFC822 source
PUT/v1/account/{account}/message/{message}Update flags/labels
DELETE/v1/account/{account}/message/{message}Delete message
PUT/v1/account/{account}/message/{message}/moveMove to another mailbox
POST/v1/account/{account}/messageUpload message to mailbox
POST/v1/account/{account}/searchSearch messages
GET/v1/account/{account}/text/{text}Get message text part
GET/v1/account/{account}/attachment/{attachment}Download attachment

Bulk Message Operations

MethodEndpointDescription
POST/v1/account/{account}/messages/moveMove multiple messages
POST/v1/account/{account}/messages/deleteDelete multiple messages

Export Operations (Beta)

MethodEndpointDescription
POST/v1/account/{account}/exportCreate new bulk message export
GET/v1/account/{account}/exportsList account exports (paginated)
GET/v1/account/{account}/export/{exportId}Get export status and details
GET/v1/account/{account}/export/{exportId}/downloadDownload completed export file
DELETE/v1/account/{account}/export/{exportId}Cancel or delete export

Mailbox Operations

MethodEndpointDescription
GET/v1/account/{account}/mailboxesList all mailboxes/folders
POST/v1/account/{account}/mailboxCreate mailbox
DELETE/v1/account/{account}/mailboxDelete mailbox

Sending Emails

MethodEndpointDescription
POST/v1/account/{account}/submitSend/queue email
GET/v1/outboxList queued emails
GET/v1/outbox/{queueId}Get queued email details
DELETE/v1/outbox/{queueId}Cancel queued email

Templates

MethodEndpointDescription
GET/v1/templatesList all templates
POST/v1/templates/templateCreate template
GET/v1/templates/template/{template}Get template
PUT/v1/templates/template/{template}Update template
DELETE/v1/templates/template/{template}Delete template
GET/v1/templates/account/{account}List account's templates

Settings & Configuration

MethodEndpointDescription
GET/v1/settingsGet all settings
POST/v1/settingsUpdate settings
GET/v1/settings/queue/{queue}Get queue configuration
PUT/v1/settings/queue/{queue}Update queue configuration

Webhooks

MethodEndpointDescription
GET/v1/webhookRoutesList webhook routes
POST/v1/webhookRoutes/webhookRouteCreate webhook route
PUT/v1/webhookRoutes/webhookRoute/{webhookRoute}Update route
DELETE/v1/webhookRoutes/webhookRoute/{webhookRoute}Delete route

OAuth2 Applications

MethodEndpointDescription
GET/v1/oauth2List OAuth2 apps
POST/v1/oauth2Register OAuth2 app
GET/v1/oauth2/{app}Get OAuth2 app
PUT/v1/oauth2/{app}Update OAuth2 app
DELETE/v1/oauth2/{app}Delete OAuth2 app

SMTP Gateway

MethodEndpointDescription
GET/v1/gatewaysList SMTP gateways
POST/v1/gatewayRegister gateway
GET/v1/gateway/{gateway}Get gateway
PUT/v1/gateway/edit/{gateway}Update gateway
DELETE/v1/gateway/{gateway}Delete gateway

Access Tokens

MethodEndpointDescription
GET/v1/tokensList all tokens
POST/v1/tokenCreate token
GET/v1/token/{token}Get token
DELETE/v1/token/{token}Delete token
GET/v1/tokens/account/{account}List account tokens

Blocklists

MethodEndpointDescription
GET/v1/blocklistsList blocklists
GET/v1/blocklist/{listId}Get blocklist entries
POST/v1/blocklist/{listId}Add to blocklist
DELETE/v1/blocklist/{listId}Remove from blocklist

Monitoring & Stats

MethodEndpointDescription
GET/v1/statsGet usage statistics
GET/v1/logs/{account}Get account logs
GET/v1/changesGet recent changes
GET/v1/licenseGet license info
GET/v1/pubsub/statusList Pub/Sub subscription status

Deliverability Testing

MethodEndpointDescription
POST/v1/delivery-test/account/{account}Start delivery test
GET/v1/delivery-test/check/{deliveryTest}Check test results

Webhook Events (24 Total)

Message Events

EventDescriptionKey Payload Fields
messageNewNew email receiveddata.id, data.from, data.to, data.subject, data.text
messageDeletedEmail deleteddata.id
messageUpdatedFlags/labels changeddata.id, data.changes
messageMissingMessage not founddata.id

Delivery Events

EventDescriptionKey Payload Fields
messageSentEmail sent successfullydata.messageId, data.response
messageDeliveryErrorDelivery attempt faileddata.error, data.job.attemptsMade
messageFailedDelivery permanently faileddata.error, data.messageId
messageBounceBounce notification receiveddata.recipient, data.bounceMessage
messageComplaintSpam complaint (ARF)data.recipient

Account Events

EventDescriptionKey Payload Fields
accountAddedAccount registeredaccount
accountDeletedAccount removedaccount
accountInitializedAccount readyaccount, state
authenticationErrorAuth failedaccount, data.error
authenticationSuccessAuth succeededaccount
connectErrorConnection failedaccount, data.error

Mailbox Events

EventDescriptionKey Payload Fields
mailboxNewFolder createddata.path
mailboxDeletedFolder deleteddata.path
mailboxResetFolder UIDVALIDITY changeddata.path

Tracking Events

EventDescriptionKey Payload Fields
trackOpenEmail openeddata.messageId, data.recipient
trackClickLink clickeddata.messageId, data.url
listUnsubscribeUser unsubscribeddata.recipient
listSubscribeUser re-subscribeddata.recipient

Export Events

EventDescriptionKey Payload Fields
exportCompletedExport finished successfullydata.exportId, data.messagesExported, data.bytesWritten
exportFailedExport faileddata.exportId, data.error

Common Patterns

Pattern 1: Register an IMAP/SMTP Account

curl -X POST "https://emailengine.example.com/v1/account" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"account": "user123",
"name": "John Doe",
"email": "john@example.com",
"imap": {
"host": "imap.example.com",
"port": 993,
"secure": true,
"auth": {
"user": "john@example.com",
"pass": "password"
}
},
"smtp": {
"host": "smtp.example.com",
"port": 465,
"secure": true,
"auth": {
"user": "john@example.com",
"pass": "password"
}
}
}'

Pattern 2: Register OAuth2 Account (Gmail/Outlook/Mail.ru)

curl -X POST "https://emailengine.example.com/v1/account" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"account": "user123",
"email": "john@gmail.com",
"oauth2": {
"provider": "OAUTH_APP_ID",
"refreshToken": "REFRESH_TOKEN",
"auth": {
"user": "john@gmail.com"
}
}
}'

Pattern 3: Send a Simple Email

curl -X POST "https://emailengine.example.com/v1/account/user123/submit" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"to": [{"address": "recipient@example.com", "name": "Recipient"}],
"subject": "Hello",
"text": "Plain text body",
"html": "<p>HTML body</p>"
}'

Pattern 4: Send Email with Attachments

curl -X POST "https://emailengine.example.com/v1/account/user123/submit" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"to": [{"address": "recipient@example.com"}],
"subject": "Document attached",
"text": "Please find the document attached.",
"attachments": [
{
"filename": "document.pdf",
"content": "BASE64_ENCODED_CONTENT",
"contentType": "application/pdf"
}
]
}'

Pattern 5: Reply to an Email

curl -X POST "https://emailengine.example.com/v1/account/user123/submit" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"to": [{"address": "original-sender@example.com"}],
"subject": "Re: Original Subject",
"text": "My reply",
"reference": {
"message": "ORIGINAL_MESSAGE_ID",
"action": "reply"
}
}'

Pattern 6: Forward an Email

curl -X POST "https://emailengine.example.com/v1/account/user123/submit" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"to": [{"address": "forward-to@example.com"}],
"subject": "Fwd: Original Subject",
"text": "Forwarding this email",
"reference": {
"message": "ORIGINAL_MESSAGE_ID",
"action": "forward"
}
}'

Pattern 7: Search Messages

curl -X POST "https://emailengine.example.com/v1/account/user123/search" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"search": {
"from": "sender@example.com",
"subject": "invoice",
"unseen": true,
"since": "2024-01-01"
}
}'

Pattern 8: Configure Webhooks

curl -X POST "https://emailengine.example.com/v1/settings" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"webhooks": "https://your-app.com/webhooks",
"webhooksEnabled": true,
"webhookEvents": ["messageNew", "messageSent", "messageFailed"]
}'

Pattern 9: Handle Webhook (Node.js)

app.post('/webhooks', express.json(), (req, res) => {
const { event, account, data } = req.body;

// Acknowledge immediately
res.status(200).json({ success: true });

// Process asynchronously
switch (event) {
case 'messageNew':
// New email: data.id, data.from, data.to, data.subject
break;
case 'messageSent':
// Email sent: data.messageId
break;
case 'messageFailed':
// Delivery failed: data.error
break;
}
});

Pattern 10: List and Paginate Messages

# First page (20 messages)
curl "https://emailengine.example.com/v1/account/user123/messages?path=INBOX&page=0&pageSize=20" \
-H "Authorization: Bearer YOUR_TOKEN"

# Next page
curl "https://emailengine.example.com/v1/account/user123/messages?path=INBOX&page=1&pageSize=20" \
-H "Authorization: Bearer YOUR_TOKEN"

Pattern 11: Mail Merge (Bulk Personalized Emails)

curl -X POST "https://emailengine.example.com/v1/account/user123/submit" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"subject": "Hello {{name}}",
"html": "<p>Dear {{name}}, your order #{{orderId}} is ready.</p>",
"mailMerge": [
{
"to": [{"address": "alice@example.com"}],
"params": {"name": "Alice", "orderId": "1001"}
},
{
"to": [{"address": "bob@example.com"}],
"params": {"name": "Bob", "orderId": "1002"}
}
]
}'

Pattern 12: Generate Hosted Authentication Form

# Generate form URL
curl -X POST "https://emailengine.example.com/v1/authentication/form" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"account": "new-user",
"name": "New User",
"redirectUrl": "https://your-app.com/settings"
}'

# Response: {"url": "https://emailengine.example.com/accounts/new?data=..."}
# Redirect user to this URL to complete authentication

Account Types

TypeValueDescriptionRequirements
IMAP/SMTPimapStandard email protocolHost, port, credentials
Gmail OAuth2gmailGmail via OAuth2 + IMAPOAuth2 app, refresh token
Gmail APIgmailGmail native APIOAuth2 app, Cloud Pub/Sub
Gmail Service AccountgmailServiceGoogle Workspace domain-wideService account key
Outlook OAuth2outlookMicrosoft via OAuth2Azure AD app, refresh token
MS Graph APIoutlookMicrosoft native APIAzure AD app, graph subscription
Outlook Application AccessoutlookServiceMicrosoft 365 via client credentialsAzure AD app, tenant ID
Mail.ru OAuth2mailRuMail.ru via OAuth2 + IMAPOAuth2 app, refresh token
Generic OAuth2oauth2Generic OAuth2 providerOAuth2 app configuration

Account States

StateDescriptionNext Steps
initBeing initializedWait
syncingInitial sync in progressWait
connectingEstablishing connectionWait
connectedActive and operationalReady for API calls
disconnectedConnection lostWill auto-reconnect
authenticationErrorInvalid credentialsUpdate credentials
connectErrorNetwork/server errorCheck connectivity
unsetOAuth2 not completedComplete OAuth2 flow

Error Handling

HTTP Status Codes

CodeMeaningAction
200Success-
400Bad RequestCheck request parameters
401UnauthorizedVerify API token
403ForbiddenCheck token permissions
404Not FoundVerify account/message ID
409ConflictDuplicate account ID
429Rate LimitedRetry with backoff
500Server ErrorRetry after delay
503UnavailableService restarting, retry

Error Response Format

{
"error": "Human-readable message",
"code": "ErrorCode",
"statusCode": 400
}

Common Error Codes

CodeDescription
AccountNotFoundAccount doesn't exist
MessageNotFoundMessage doesn't exist
InvalidRequestRequest validation failed
AuthenticationRequiredMissing API token
RateLimitExceededToo many requests
ConnectionErrorCan't connect to mail server

Decision Trees

Choosing Account Type

Gmail API vs Gmail IMAP

MS Graph vs Outlook IMAP

Key Settings (via POST /v1/settings)

SettingTypeDescription
webhooksstringWebhook URL
webhooksEnabledbooleanEnable webhook delivery
webhookEventsarrayEvent types to trigger
inboxNewOnlybooleanOnly trigger messageNew for Inbox folder
serviceUrlstringPublic URL of EmailEngine instance
serviceSecretstringHMAC secret for webhook signature verification
resolveGmailCategoriesbooleanDetect Gmail tabs (Primary, Social, etc.) for IMAP
smtpEhloNamestringCustom EHLO hostname for SMTP connections
ignoreMailCertErrorsbooleanAccept invalid TLS certificates
trackOpensbooleanEnable email open tracking
trackClicksbooleanEnable click tracking
imapIndexerstringIndexing strategy: full or fast
scriptEnvstringJSON environment variables for pre-processing scripts
httpProxyEnabledbooleanRoute outbound HTTP/HTTPS requests through proxy
httpProxyUrlstringHTTP/SOCKS proxy URL for outbound requests
pageBrandNamestringCustom brand name displayed in page titles
notifyTextbooleanInclude plain text content in webhook payloads
notifyTextSizenumberMax text size in webhook payloads (bytes)
notifyAttachmentsbooleanInclude attachments in webhook payloads
notifyAttachmentSizenumberMax attachment size in webhook payloads (bytes)
notifyCalendarEventsbooleanInclude calendar events in webhook payloads
notifyWebSafeHtmlbooleanSanitize HTML in webhook payloads
localestringUI language/locale
timezonestringDefault timezone (IANA identifier)
templateHeaderstringCustom HTML header for hosted pages
templateHtmlHeadstringCustom HTML for page head section
imapClientNamestringIMAP ID extension client name
imapClientVersionstringIMAP ID extension version
imapClientVendorstringIMAP ID extension vendor
imapClientSupportUrlstringIMAP ID extension support URL

Per-Account IMAP Settings

SettingTypeDefaultDescription
disabledbooleanfalseDisable IMAP (send-only mode)
resyncDelaynumber900Seconds between full mailbox resyncs
sentMailPathstringautoCustom Sent folder path
draftsMailPathstringautoCustom Drafts folder path
junkMailPathstringautoCustom Junk folder path
trashMailPathstringautoCustom Trash folder path
archiveMailPathstringautoCustom Archive folder path
useAuthServerbooleanfalseFetch credentials from external auth server

Environment Variables

VariableRequiredDescription
EENGINE_REDISYesRedis URL (e.g., redis://localhost:6379/8)
EENGINE_SECRETProdEncryption key for credentials (32+ hex chars)
EENGINE_PORTNoAPI port (default: 3000)
EENGINE_HOSTNoBind address (default: 127.0.0.1)
EENGINE_WORKERSNoIMAP worker count (default: 4)
EENGINE_WORKERS_WEBHOOKSNoWebhook worker count (default: 1)
EENGINE_WORKERS_SUBMITNoSubmit worker count (default: 1)
EENGINE_WORKERS_EXPORTNoExport worker count (default: 1)
EENGINE_LOG_LEVELNoLog level (trace/debug/info/warn/error)
EENGINE_FEATURE_*NoEnable feature flags (set to true)
EENGINE_CORS_MAX_AGENoCORS preflight cache duration in seconds (default: 60)
EENGINE_HTTP_PROXY_ENABLEDNoEnable HTTP proxy for outbound requests
EENGINE_HTTP_PROXY_URLNoHTTP/SOCKS proxy URL for outbound requests

Submit API Key Parameters

The POST /v1/account/{account}/submit endpoint accepts these key parameters:

ParameterTypeDescription
toarrayRecipients [{address, name}] (required)
ccarrayCC recipients
bccarrayBCC recipients
subjectstringEmail subject
textstringPlain text body
htmlstringHTML body
fromobjectOverride sender {address, name}
replyToobjectReply-to address
attachmentsarrayAttachments [{filename, content, contentType}]
headersobjectCustom headers
referenceobjectFor replies/forwards {message, action}
templatestringTemplate ID to use
mailMergearrayBulk send with personalization
sendAtstringSchedule sending (ISO 8601)
trackOpensbooleanEnable open tracking
trackClicksbooleanEnable click tracking
copybooleanSave to Sent folder (default: true)
dryRunbooleanPreview without sending
gatewaystringUse specific SMTP gateway
deliveryAttemptsnumberMax retry attempts

Search Parameters

The POST /v1/account/{account}/search endpoint accepts these search criteria:

ParameterTypeDescription
fromstringSender address/name
tostringRecipient address/name
subjectstringSubject contains
bodystringBody contains
unseenbooleanUnread only
flaggedbooleanStarred/flagged only
sincestringAfter date (YYYY-MM-DD)
beforestringBefore date (YYYY-MM-DD)
headerobjectCustom header match
emailIdstringSpecific message ID
threadIdstringSpecific thread ID

See Also