Airpost
Plugins

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.

ModuleContents
mailspring-exportsActions, stores, models, tasks, registries, extension base classes, Engine, AI, localized, utilities
mailspring-component-kitReact components, including the UI kit
mailspring-storeBaseStore, for your own Flux stores
mailspring-observablesThe 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.

StoreUseful members
AccountStoreaccounts(), accountIds(), accountForId(id), accountForEmail(email), accountForItems(threads), isMyEmail(email), emailAddresses(), aliases()
MessageStoreitems() (messages in the open thread), thread(), threadId()
FocusedContentStorefocused('thread' | 'message'), focusedId(collection), keyboardCursor(collection)
FocusedPerspectiveStorecurrent() (the mailbox perspective), sidebarAccountIds()
CategoryStorecategories(account), byId(account, id), getInboxCategory(account), getArchiveCategory(account), getTrashCategory(account), getSpamCategory(account), getCategoryByRole(account, role), userCategories(account)
ContactStoresearchContacts(text, { limit }), topContacts({ limit }), parseContactsInString(text)
DraftStoresessionForClientId(headerMessageId), isSendingDraft(headerMessageId)
TaskQueuequeue(), completed(), allTasks(), findTasks(...), waitForPerformLocal(task), waitForPerformRemote(task)
SignatureStoregetSignatures(), selectedSignature(), getDefaults()
WorkspaceStoreLocation, Sheet, defineSheet(...), undefineSheet(id)
PreferencesUIStoreTabItem, registerPreferencesTab(tab), unregisterPreferencesTab(tabOrId)
UndoRedoStoreThe undo toast and the engine’s undo log
CapabilityStore, useCapabilityWhat 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([...]):

AreaTasks
MailChangeStarredTask, ChangeUnreadTask, ChangeFolderTask, ChangeLabelsTask, ChangeMailTask, IntentTask, ExpungeAllInFolderTask
Drafts and sendingSyncbackDraftTask, SendDraftTask, DestroyDraftTask
Folders and labelsSyncbackCategoryTask, DestroyCategoryTask, ChangeRoleMappingTask
MetadataSyncbackMetadataTask
Raw messagesGetMessageRFC2822Task, GetManyRFC2822Task
CalendarSyncbackEventTask, DestroyEventTask, EventRSVPTask
ContactsSyncbackContactTask, DestroyContactTask, SyncbackContactGroupTask, DestroyContactGroupTask, ChangeContactGroupMembershipTask
OtherDestroyModelTask, 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:

GroupActions
TasksqueueTask, queueTasks, cancelTask, queueUndoOnlyTask
ComposingcomposeReply, composeForward, composeNewBlankDraft, composeNewDraftToRecipient, composePopoutDraft, sendDraft, destroyDraft, sendQuickReply, draftDeliverySucceeded, draftDeliveryFailed
NavigationfocusMailboxPerspective, setFocus, setCursorPosition, selectRootSheet, pushSheet, popSheet, popToRootSheet, popoutThread, focusContact
UIopenPopover, closePopover, openModal, closeModal, openPreferences, switchPreferencesTab, playSound
MessagestoggleMessageIdExpanded, toggleAllMessagesExpanded, printThread, findInThread
AttachmentsaddAttachment, removeAttachment, fetchFile, fetchAndOpenFile, fetchAndSaveFile, quickPreviewFile
SearchsearchQuerySubmitted, searchQueryChanged, searchCompleted
Rules, signatures, templatesaddMailRule, 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.

RoleWhereProps
Composer:ActionButtonComposer action bardraft, threadId, headerMessageId, session, isValidDraft
Composer:ActionBarWorkspaceArea above the composer action barcomposer state
Composer:FooterBelow the composer bodydraft, threadId, headerMessageId, session
Composer:FromFieldComponentsBeside the From fieldthe From field’s props, including draft
Composer:RecipientChipInside each recipient chip (composer and event attendees)contact, collapsed
ThreadActionsToolbarButtonThread toolbar, for the selectionitems, selection, thread (the first item)
DraftActionsToolbarButtonDrafts list toolbarselection, items
ThreadListIconIcon column of thread list rowsthread
ThreadListQuickActionHover actions on thread list rowsthread
ThreadListTimestampReplaces the row timestampthread
Thread:MailLabelExtra labels on a threadthread, messages
DraftList:DraftStatusStatus in the drafts listdraft
MessageListHeadersAbove the message listthread, messages
MessageHeaderAbove each messagemessage, thread, messages
MessageHeaderStatusIn each message headermessage, thread, detailedHeaders
MessageFooterStatusBelow each messagemessage, thread, detailedHeaders
message:BodyHeaderInside the message body, above the contentmessage
MessageListSidebar:ContactCardContact card in the reading pane sidebarcontact
NavRail:ItemItems in the nav railnone
RootSidebar:NotificationsNotification area of the sidebarnone
Calendar:EventInside each calendar eventevent
Calendar:Day:Banner, Calendar:Week:BannerAbove the day, week, month and agenda viewsnone

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.

RegistryMethodCalled withReturns
ComposersendActions()Extra send actions (title, performSendAction, isEnabled, iconUrl)
ComposerwarningsForSending({ draft })Strings for the “Send … ?” confirmation
ComposerprepareNewDraft({ draft })A new draft before it showsNothing; mutate the draft
ComposerapplyTransformsForSending({ draft, draftBodyRootNode, recipient })Before sendA changed draft, or a promise of one
MessageViewformatMessageBody({ message })Before renderNothing; change message.body
MessageViewallowsRemoteImages({ message })Before rendertrue, false, or undefined for no opinion
MessageViewrenderedMessageBodyIntoDocument({ body, message })After renderNothing (see below)
MessageViewfilterMessageFiles({ message, files })Attachment listThe files to show
ThreadListcssClassNamesForThreadListItem(thread)Each rowClass names added to the row
ThreadListcssClassNamesForThreadListIcon(thread)Each row’s iconClass names that replace the default icon
AccountSidebarsidebarItem(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:

MethodDoes
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

RegistryPurpose
SoundRegistryNotification sounds: register(), playSound()
ServiceRegistryShare a service between plugins: registerService(), withService()
DatabaseObjectRegistryRegister 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.

MemberDoes
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.capabilitiesWhat the engine can do now, such as capabilities.integrations.translation.available. null while disconnected
Engine.connectedWhether 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:

VersionAdded
1.27.0Engine, airpost.engineMethods; renderedMessageBodyIntoDocument gets body instead of the document
1.28.0AI and the AI settings
1.30.0The engine runs mail rules (rules.*)
1.31.0ComponentRegistry.listenShared
1.32.0The engine builds and edits calendar events and vCards
1.33.0Preferences building blocks in mailspring-component-kit
1.34.0TestUtils (replacing MailspringTestUtils)
1.35.0Airpost names (airpost-asset://, engines.airpost, AppEnv.engineBridge); the Webview component renders nothing
1.37.0The engine builds every new, reply, forward and mailto draft
1.38.0The engine validates drafts before send; isValidDraft returns a Promise
1.39.0IntentTask 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.