Plugin API
The modules plugins import, the registries and extension points, the Engine API, and how the plugin API is versioned.
The desktop’s plugin API (v1) keeps the module names it inherited from Mailspring, because existing plugins depend on them. The current version is 1.39.0.
Modules
Plugins import these bare module names. The app puts them on the module path at runtime.
| Module | Contents |
|---|---|
mailspring-exports | Actions, stores, models, tasks, registries, extension base classes, Engine, AI, localized, utilities |
mailspring-component-kit | React components, including the UI kit |
mailspring-store | BaseStore, for your own Flux stores |
mailspring-observables | The RxJS helpers, such as Rx.Observable.fromQuery |
The type declarations are apps/desktop/src/packages/api/mailspring-exports.d.ts and mailspring-component-kit.d.ts.
Some names have Airpost equivalents that work the same: airpost-asset://<package>/<path> for assets (mailspring:// is an alias), engines.airpost in package.json (engines.mailspring is read too), and AppEnv.engineBridge (AppEnv.mailsyncBridge is an alias). Use the Airpost names in new code.
Data
The desktop never writes to the database. To change something, queue a task; to read, query.
import { Actions, DatabaseStore, Thread, ChangeStarredTask, QuerySubscription } from 'mailspring-exports';
// Read
const threads = await DatabaseStore.findAll(Thread).where({ unread: true }).limit(20);
// Watch
const sub = new QuerySubscription(DatabaseStore.findAll(Thread).where({ unread: true }));
sub.addCallback(threads => console.log(threads.length));
// Write
Actions.queueTask(new ChangeStarredTask({ threads, starred: true }));
Mail actions such as archive and move are the engine’s intents: TaskFactory and the mailbox perspectives return an IntentTask to queue with Actions.queueTask. TaskQueue.waitForPerformRemote(task) resolves when a task has fully completed.
To store your own data on a thread or message, use plugin metadata: SyncbackMetadataTask with your plugin id as pluginId, read back with model.metadataForPluginId('<plugin id>'). Metadata with an expiration field is what service plugins act on.
Stores
Stores are Flux singletons from mailspring-exports. Read with their getters, and subscribe with Store.listen(callback), which returns an unsubscribe function. These are the ones plugins use most; the rest are listed in apps/desktop/src/packages/api/mailspring-exports.js.
| Store | Useful members |
|---|---|
AccountStore | accounts(), accountIds(), accountForId(id), accountForEmail(email), accountForItems(threads), isMyEmail(email), emailAddresses(), aliases() |
MessageStore | items() (messages in the open thread), thread(), threadId() |
FocusedContentStore | focused('thread' | 'message'), focusedId(collection), keyboardCursor(collection) |
FocusedPerspectiveStore | current() (the mailbox perspective), sidebarAccountIds() |
CategoryStore | categories(account), byId(account, id), getInboxCategory(account), getArchiveCategory(account), getTrashCategory(account), getSpamCategory(account), getCategoryByRole(account, role), userCategories(account) |
ContactStore | searchContacts(text, { limit }), topContacts({ limit }), parseContactsInString(text) |
DraftStore | sessionForClientId(headerMessageId), isSendingDraft(headerMessageId) |
TaskQueue | queue(), completed(), allTasks(), findTasks(...), waitForPerformLocal(task), waitForPerformRemote(task) |
SignatureStore | getSignatures(), selectedSignature(), getDefaults() |
WorkspaceStore | Location, Sheet, defineSheet(...), undefineSheet(id) |
PreferencesUIStore | TabItem, registerPreferencesTab(tab), unregisterPreferencesTab(tabOrId) |
UndoRedoStore | The undo toast and the engine’s undo log |
CapabilityStore, useCapability | What the engine and server can do now |
Other exported stores: BadgeStore, ModalStore, PopoverStore, OutboxStore, LabelColorStore, MailRulesStore, SendActionsStore, ThreadCountsStore, AttachmentStore, OnlineStatusStore, FocusedContactsStore, FolderSyncProgressStore, SearchableComponentStore, DraftEditingSession, MessageBodyProcessor.
To write your own store, extend BaseStore from mailspring-store and call this.trigger() when it changes.
Models and tasks
Models: Thread, Message, Contact, ContactBook, ContactGroup, Account, Category, Folder, Label, File, Event, Calendar, ProviderSyncbackRequest. Query them with DatabaseStore.find, findBy, findAll and count; register your own with DatabaseObjectRegistry.
Tasks, all queued with Actions.queueTask(task) or Actions.queueTasks([...]):
| Area | Tasks |
|---|---|
ChangeStarredTask, ChangeUnreadTask, ChangeFolderTask, ChangeLabelsTask, ChangeMailTask, IntentTask, ExpungeAllInFolderTask | |
| Drafts and sending | SyncbackDraftTask, SendDraftTask, DestroyDraftTask |
| Folders and labels | SyncbackCategoryTask, DestroyCategoryTask, ChangeRoleMappingTask |
| Metadata | SyncbackMetadataTask |
| Raw messages | GetMessageRFC2822Task, GetManyRFC2822Task |
| Calendar | SyncbackEventTask, DestroyEventTask, EventRSVPTask |
| Contacts | SyncbackContactTask, DestroyContactTask, SyncbackContactGroupTask, DestroyContactGroupTask, ChangeContactGroupMembershipTask |
| Other | DestroyModelTask, and TaskFactory for the common mail tasks |
Actions
Actions holds the app’s Flux actions, defined in apps/desktop/src/data/actions.ts. Call one as a function to fire it, or Actions.someAction.listen(cb) to react (it returns an unsubscribe function). The ones plugins use most:
| Group | Actions |
|---|---|
| Tasks | queueTask, queueTasks, cancelTask, queueUndoOnlyTask |
| Composing | composeReply, composeForward, composeNewBlankDraft, composeNewDraftToRecipient, composePopoutDraft, sendDraft, destroyDraft, sendQuickReply, draftDeliverySucceeded, draftDeliveryFailed |
| Navigation | focusMailboxPerspective, setFocus, setCursorPosition, selectRootSheet, pushSheet, popSheet, popToRootSheet, popoutThread, focusContact |
| UI | openPopover, closePopover, openModal, closeModal, openPreferences, switchPreferencesTab, playSound |
| Messages | toggleMessageIdExpanded, toggleAllMessagesExpanded, printThread, findInThread |
| Attachments | addAttachment, removeAttachment, fetchFile, fetchAndOpenFile, fetchAndSaveFile, quickPreviewFile |
| Search | searchQuerySubmitted, searchQueryChanged, searchCompleted |
| Rules, signatures, templates | addMailRule, updateMailRule, deleteMailRule, upsertSignature, selectSignature, insertTemplateId, createTemplate |
Preferences tabs
import { PreferencesUIStore, localized } from 'mailspring-exports';
const tab = new PreferencesUIStore.TabItem({
tabId: 'MyPlugin',
displayName: localized('My Plugin'),
componentClassFn: () => require('./preferences').default,
order: 50, // lower sorts first
group: 'plugins', // the default
keywords: ['extra', 'search', 'words'],
});
PreferencesUIStore.registerPreferencesTab(tab);
// in deactivate():
PreferencesUIStore.unregisterPreferencesTab(tab.tabId);
Build the page with the settings building blocks.
ComponentRegistry
Adds React components to named slots. Every component needs a static displayName.
import { ComponentRegistry, WorkspaceStore } from 'mailspring-exports';
ComponentRegistry.register(MyButton, { role: 'ThreadActionsToolbarButton' });
ComponentRegistry.register(MySidebar, { location: WorkspaceStore.Location.MessageListSidebar });
ComponentRegistry.register(MyIcon, { role: 'ThreadListIcon', modes: ['list', 'split'] });
The roles below are the ones the app renders with InjectedComponent or InjectedComponentSet. Your component receives the listed props.
| Role | Where | Props |
|---|---|---|
Composer:ActionButton | Composer action bar | draft, threadId, headerMessageId, session, isValidDraft |
Composer:ActionBarWorkspace | Area above the composer action bar | composer state |
Composer:Footer | Below the composer body | draft, threadId, headerMessageId, session |
Composer:FromFieldComponents | Beside the From field | the From field’s props, including draft |
Composer:RecipientChip | Inside each recipient chip (composer and event attendees) | contact, collapsed |
ThreadActionsToolbarButton | Thread toolbar, for the selection | items, selection, thread (the first item) |
DraftActionsToolbarButton | Drafts list toolbar | selection, items |
ThreadListIcon | Icon column of thread list rows | thread |
ThreadListQuickAction | Hover actions on thread list rows | thread |
ThreadListTimestamp | Replaces the row timestamp | thread |
Thread:MailLabel | Extra labels on a thread | thread, messages |
DraftList:DraftStatus | Status in the drafts list | draft |
MessageListHeaders | Above the message list | thread, messages |
MessageHeader | Above each message | message, thread, messages |
MessageHeaderStatus | In each message header | message, thread, detailedHeaders |
MessageFooterStatus | Below each message | message, thread, detailedHeaders |
message:BodyHeader | Inside the message body, above the content | message |
MessageListSidebar:ContactCard | Contact card in the reading pane sidebar | contact |
NavRail:Item | Items in the nav rail | none |
RootSidebar:Notifications | Notification area of the sidebar | none |
Calendar:Event | Inside each calendar event | event |
Calendar:Day:Banner, Calendar:Week:Banner | Above the day, week, month and agenda views | none |
The injection sites are in apps/desktop/src/features/* and src/components/; search for matching={{ role: to find one and the exact props it passes. A ComponentRegistry descriptor takes role or roles, location or locations, and mode or modes, and the component must have a unique displayName. To see every injection point in a running window, call $m.ComponentRegistry.toggleComponentRegions() in the developer console.
Locations are the columns of the main window’s sheets, defined in src/data/stores/workspace.ts: the Threads sheet has RootSidebar, ThreadList, MessageList and MessageListSidebar (which ones show depends on the mode: list, split or splitVertical), and the Thread sheet has MessageList and MessageListSidebar. Each location also has a .Toolbar for its toolbar, for example WorkspaceStore.Location.ThreadList.Toolbar.
ExtensionRegistry
Behaviour hooks, registered as subclasses of an extension base class:
import { ExtensionRegistry } from 'mailspring-exports';
ExtensionRegistry.Composer.register(MyComposerExtension);
ExtensionRegistry.MessageView.register(MyMessageExtension);
ExtensionRegistry.ThreadList.register(MyThreadListExtension);
ExtensionRegistry.AccountSidebar.register(MySidebarExtension);
ComposerExtension is covered in Composer plugins.
Extension hooks
Each registry calls static methods on the classes you register. The extension needs a unique name (a class’s name works); register(ext, { priority }) orders them.
| Registry | Method | Called with | Returns |
|---|---|---|---|
Composer | sendActions() | Extra send actions (title, performSendAction, isEnabled, iconUrl) | |
Composer | warningsForSending({ draft }) | Strings for the “Send … ?” confirmation | |
Composer | prepareNewDraft({ draft }) | A new draft before it shows | Nothing; mutate the draft |
Composer | applyTransformsForSending({ draft, draftBodyRootNode, recipient }) | Before send | A changed draft, or a promise of one |
MessageView | formatMessageBody({ message }) | Before render | Nothing; change message.body |
MessageView | allowsRemoteImages({ message }) | Before render | true, false, or undefined for no opinion |
MessageView | renderedMessageBodyIntoDocument({ body, message }) | After render | Nothing (see below) |
MessageView | filterMessageFiles({ message, files }) | Attachment list | The files to show |
ThreadList | cssClassNamesForThreadListItem(thread) | Each row | Class names added to the row |
ThreadList | cssClassNamesForThreadListIcon(thread) | Each row’s icon | Class names that replace the default icon |
AccountSidebar | sidebarItem(accountIds) | Each account section, and the unified one | { id, name, iconName, perspective, insertAtTop }, or null |
The base classes are in apps/desktop/src/packages/composer-extension.ts and message-view-extension.ts; ThreadList and AccountSidebar extensions are plain objects or classes with the method.
MessageViewExtension
import { MessageViewExtension } from 'mailspring-exports';
export default class MyMessageExtension extends MessageViewExtension {
// Change the HTML before it renders
static formatMessageBody({ message }) {
message.body = processHTML(message.body);
}
// Work on the rendered body through `body`
static async renderedMessageBodyIntoDocument({ body, message }) {
const links = await body.querySelectorAll('a[href^="https://tracker.example"]');
for (const link of links) {
await body.setAttributes(link.ref, { title: 'Tracked link' });
await body.insertElement(link.ref, 'afterend', 'span', { class: 'tracked' }, ' (tracked)');
}
}
// Hide some attachments
static filterMessageFiles({ message, files }) {
return files.filter(f => !f.filename.endsWith('.sig'));
}
}
The message body renders in a sandboxed, cross-origin frame, so there is no document in renderedMessageBodyIntoDocument. Reading it throws. Use body, a MessageBody:
| Method | Does |
|---|---|
querySelectorAll(selector) | Elements matching a CSS selector, as {ref, tagName, attributes, text} |
setAttributes(ref, attributes) | Sets attributes (null removes one). Event handler attributes are refused |
insertElement(ref, position, tagName, attributes?, text?) | Adds an element and returns its ref. Scripts, frames, forms, styles and document-level elements are refused |
getBoundingClientRect(ref) | The element’s box in window coordinates, for popovers |
addEventListener(ref, 'click' | 'mousedown', cb) | Calls cb({rect}) on click |
Every call returns a promise. Refs stay valid until the message renders again.
Other registries
| Registry | Purpose |
|---|---|
SoundRegistry | Notification sounds: register(), playSound() |
ServiceRegistry | Share a service between plugins: registerService(), withService() |
DatabaseObjectRegistry | Register custom model classes |
See Preferences tabs to add a tab.
Engine
Engine in mailspring-exports is the plugin’s way to the sync engine. Each window has its own connection; requests made while the engine is down reject.
| Member | Does |
|---|---|
Engine.request(method, params) | Calls a socket method (reads, query, metadata.list, integrations.*, …) and resolves with the result, or rejects with the engine’s error (code, message, data) |
Engine.subscribe(filter, cb) | Calls cb for each notification except deltas (use DatabaseStore.listen for those). filter is {methods?, accounts?}. Returns a disposable |
Engine.features, Engine.has(feature) | Features the engine announced. Gate on these, not on versions |
Engine.capabilities | What the engine can do now, such as capabilities.integrations.translation.available. null while disconnected |
Engine.connected | Whether the connection is up |
Engine.onDidChange(cb) | Called when the engine connects, goes away, or its capabilities change. Returns a disposable |
import { Engine } from 'mailspring-exports';
let sub;
export function activate() {
sub = Engine.subscribe({ methods: ['mail.new'] }, ({ params }) => {
console.log('new mail in', params.accountId);
});
}
export function deactivate() {
sub.dispose();
}
hello and subscribe belong to the window’s connection and are refused. The local-only methods (accounts, secrets, credentials, server.*, engine.logs.tail, engine.setLogLevel, engine.resetDatabase, engine.shutdown) are refused unless your package.json lists them and the user allows it:
{ "airpost": { "engineMethods": ["engine.logs.tail"] } }
The first call asks the user. A yes is remembered in core.plugins.engineMethodApprovals; a no lasts until the app restarts. This prompt guards against accidents, not against a malicious plugin.
Configuration
A plugin can declare a config schema. Values live under the plugin’s name.
export const config = {
myOption: { type: 'string', default: 'value', description: 'What it does' },
};
export function activateConfig() {
AppEnv.config.onDidChange('my-plugin.myOption', value => { /* ... */ });
}
Versioning
engines.airpost is a semver range matched against the plugin API version (apiVersion in mailspring-exports, PLUGIN_API_VERSION in apps/desktop/src/packages/api-version.ts). It moves with the API, not the app: a minor bump for additions, a major one only when deprecated exports are removed. Set the lowest version that has what you use, for example "^1.27.0" if you use Engine.
Recent additions:
| Version | Added |
|---|---|
| 1.27.0 | Engine, airpost.engineMethods; renderedMessageBodyIntoDocument gets body instead of the document |
| 1.28.0 | AI and the AI settings |
| 1.30.0 | The engine runs mail rules (rules.*) |
| 1.31.0 | ComponentRegistry.listenShared |
| 1.32.0 | The engine builds and edits calendar events and vCards |
| 1.33.0 | Preferences building blocks in mailspring-component-kit |
| 1.34.0 | TestUtils (replacing MailspringTestUtils) |
| 1.35.0 | Airpost names (airpost-asset://, engines.airpost, AppEnv.engineBridge); the Webview component renders nothing |
| 1.37.0 | The engine builds every new, reply, forward and mailto draft |
| 1.38.0 | The engine validates drafts before send; isValidDraft returns a Promise |
| 1.39.0 | IntentTask and the engine’s undo log |
The comment above PLUGIN_API_VERSION lists each version’s changes and deprecations in full. Deprecated exports and the LESS compatibility path are removed in 2.0.0. A v2 API is being designed; v1 keeps working, unchanged, until then.