Skip to content

📧✨ Beautiful email. For everyone.

feat: send from email aliases (#35)

Paul Koeck395966637b8d
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 3ed9e91..d17f9eb 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -229,6 +229,7 @@ else {
reconnect: service.reconnect,
updateAccount: service.updateAccount,
updateAccountDetails: service.updateAccountDetails,
+ setAliases: service.setAliases,
mailboxes: service.mailboxes,
identities: service.identities,
query: service.query,
diff --git a/apps/desktop/src/main/service.ts b/apps/desktop/src/main/service.ts
index a842d97..dcc142e 100644
--- a/apps/desktop/src/main/service.ts
+++ b/apps/desktop/src/main/service.ts
@@ -15,6 +15,8 @@ import {
type Account,
type AccountAppearance,
type Address,
+ type Alias,
+ type AliasInput,
type Settings,
type ConnectInput,
type ConnectionCheck,
@@ -440,6 +442,11 @@ export class MailService {
account.name = known.name
account.senderName = known.senderName
} else account.senderName = input.senderName?.trim() || undefined
+ // Aliases belong to the account rather than its login, so editing the login keeps them.
+ const aliases = known?.aliases?.filter(
+ (a) => a.email.toLowerCase() !== account.email.toLowerCase(),
+ )
+ if (aliases?.length) account.aliases = aliases
used.push(account.color)
}
const keep = (value?: string) =>
@@ -587,15 +594,10 @@ export class MailService {
this.emit({ type: 'changed', accountId })
return review
}
- updateAccount = async (accountId: string, appearance: AccountAppearance): Promise<Account[]> => {
+ /** Saves a change to one account's own settings, which never needs signing in again. */
+ private async editAccount(accountId: string, patch: (a: Account) => Partial<Account>) {
const account = this.account(accountId)
- if (appearance.image) {
- const [, type, data] = appearance.image.match(/^data:([^;]+);base64,(.*)$/)!
- if (rasterType(Buffer.from(data, 'base64')) !== type)
- throw new Error('This picture could not be read. Choose a PNG, JPEG or WebP image.')
- }
- const apply = (a: Account): Account =>
- a.id === accountId ? { ...a, seed: appearance.seed, image: appearance.image } : a
+ const apply = (a: Account): Account => (a.id === accountId ? { ...a, ...patch(a) } : a)
this.accounts = this.accounts.map(apply)
this.connections = this.connections.map((c) =>
c.id === account.connectionId ? { ...c, accounts: c.accounts.map(apply) } : c,
@@ -604,23 +606,35 @@ export class MailService {
this.emit({ type: 'accounts', accounts: this.accounts })
return this.accounts
}
- updateAccountDetails = async (accountId: string, details: AccountDetails): Promise<Account[]> => {
+ updateAccount = async (accountId: string, appearance: AccountAppearance): Promise<Account[]> => {
+ if (appearance.image) {
+ const [, type, data] = appearance.image.match(/^data:([^;]+);base64,(.*)$/)!
+ if (rasterType(Buffer.from(data, 'base64')) !== type)
+ throw new Error('This picture could not be read. Choose a PNG, JPEG or WebP image.')
+ }
+ return this.editAccount(accountId, () => ({ seed: appearance.seed, image: appearance.image }))
+ }
+ updateAccountDetails = async (accountId: string, details: AccountDetails): Promise<Account[]> =>
+ this.editAccount(accountId, (a) => ({
+ name: details.name.trim() || a.name,
+ senderName: details.senderName.trim() || undefined,
+ }))
+ setAliases = async (accountId: string, input: AliasInput[]): Promise<Account[]> => {
const account = this.account(accountId)
- const apply = (a: Account): Account =>
- a.id === accountId
- ? {
- ...a,
- name: details.name.trim() || a.name,
- senderName: details.senderName.trim() || undefined,
- }
- : a
- this.accounts = this.accounts.map(apply)
- this.connections = this.connections.map((c) =>
- c.id === account.connectionId ? { ...c, accounts: c.accounts.map(apply) } : c,
- )
- await this.saveConnections()
- this.emit({ type: 'accounts', accounts: this.accounts })
- return this.accounts
+ if (account.protocol !== 'imap')
+ throw new Error('This server manages its own sending addresses.')
+ const taken = new Set([account.email.toLowerCase()])
+ const aliases = input.map((alias): Alias => {
+ const email = alias.email.trim()
+ if (taken.has(email.toLowerCase()))
+ throw new Error(email + ' is already one of this account’s addresses.')
+ taken.add(email.toLowerCase())
+ // Only a known ID is kept, so drafts and signatures stay with the alias they belong to.
+ const id = account.aliases?.some((a) => a.id === alias.id) ? alias.id! : randomUUID()
+ const name = alias.name?.trim()
+ return { id, email, ...(name ? { name } : {}) }
+ })
+ return this.editAccount(accountId, () => ({ aliases: aliases.length ? aliases : undefined }))
}
disconnect = async (id: string): Promise<void> => {
const accountIds = new Set(this.accounts.filter((a) => a.connectionId === id).map((a) => a.id))
@@ -1097,9 +1111,10 @@ export class MailService {
mime: journal.mime ? await readFile(this.mimePath(journal.draftId)) : undefined,
}
}
- /** A unique Message-ID per attempt, on the sender's own domain. */
- private messageIdFor(account: Account) {
- const domain = account.email
+ /** A unique Message-ID per attempt, on the domain of the address the message is from. */
+ private messageIdFor(account: Account, identityId: string) {
+ const email = account.aliases?.find((a) => a.id === identityId)?.email || account.email
+ const domain = email
.split('@')[1]
?.toLowerCase()
.replace(/[^a-z0-9.-]/g, '')
@@ -1149,7 +1164,7 @@ export class MailService {
subject: draft.subject,
messageId:
provider.capabilities.sentCopy === 'client'
- ? this.messageIdFor(account)
+ ? this.messageIdFor(account, draft.identityId)
: draft.id + '@inlark.local',
state: 'preparing',
at: new Date().toISOString(),
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index cc939e0..755f4cd 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -14,6 +14,7 @@ const methods = [
'reconnect',
'updateAccount',
'updateAccountDetails',
+ 'setAliases',
'mailboxes',
'identities',
'query',
diff --git a/apps/desktop/src/renderer/src/Aliases.tsx b/apps/desktop/src/renderer/src/Aliases.tsx
new file mode 100644
index 0000000..a9c1308
--- /dev/null
+++ b/apps/desktop/src/renderer/src/Aliases.tsx
@@ -0,0 +1,189 @@
+import { cn } from '@inlark/ui'
+import { useState } from 'react'
+import { z } from 'zod'
+import { AlertCircle, Plus, X } from '@inlark/ui/icons'
+import { Button, IconButton, Modal, Spinner } from '@inlark/ui'
+import { friendlyError, type Account, type AliasInput } from '@inlark/core'
+import { api } from './api'
+import { queryClient } from './cache'
+
+const emailSchema = z.email()
+const row = cn(
+ 'alias-row grid grid-cols-[minmax(0,_1fr)_200px_32px] gap-3 items-center min-h-12.5 py-2 px-0',
+ '[&+.alias-row]:border-t [&+.alias-row]:border-solid [&+.alias-row]:border-t-border',
+ 'max-[700px]:grid-cols-[minmax(0,_1fr)_150px_32px]',
+)
+const formError =
+ 'form-error flex gap-2 text-[11px] leading-[1.6] my-3.75 mx-0 text-danger [&_svg]:shrink-0 [&_svg]:mt-[3px]'
+
+/**
+ * Settings → Accounts → Email addresses…: aliases this account may send from. They're only
+ * used here; the provider must already deliver them to this account and accept them as sender.
+ */
+export function AliasesDialog({
+ account,
+ onClose,
+ notify,
+}: {
+ account?: Account
+ onClose: () => void
+ notify: (message: string) => void
+}) {
+ const [aliases, setAliases] = useState<AliasInput[]>(account?.aliases || [])
+ const [email, setEmail] = useState('')
+ const [addError, setAddError] = useState('')
+ const [saving, setSaving] = useState(false)
+ const [error, setError] = useState('')
+ /** Why an address can't be added, if it can't. */
+ const problem = (value: string) =>
+ !emailSchema.safeParse(value).success
+ ? 'Enter a valid email address.'
+ : [account?.email || '', ...aliases.map((a) => a.email)].some(
+ (known) => known.toLowerCase() === value.toLowerCase(),
+ )
+ ? 'This address is already listed.'
+ : ''
+ /** Adds what's typed in the new address field, and returns the list including it. */
+ const add = () => {
+ const value = email.trim()
+ if (!value) return aliases
+ const reason = problem(value)
+ setAddError(reason)
+ if (reason) return undefined
+ const next = [...aliases, { email: value }]
+ setAliases(next)
+ setEmail('')
+ return next
+ }
+ return (
+ <Modal
+ open={!!account}
+ onOpenChange={(open) => {
+ if (!open && !saving) onClose()
+ }}
+ title={'Email addresses for ' + (account?.name || 'this account')}
+ description="Send from aliases or custom-domain addresses that your provider delivers to this account. Set them up with your provider first; Inlark doesn’t create them."
+ className="alias-modal w-[min(600px,_calc(100vw_-_40px))]"
+ >
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault()
+ if (!account) return
+ // An address typed but not yet added is clearly meant to be saved too.
+ const list = add()
+ if (!list) return
+ setSaving(true)
+ setError('')
+ try {
+ await api.setAliases(
+ account.id,
+ list.map((a) => ({ id: a.id, email: a.email, name: a.name?.trim() || undefined })),
+ )
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ['bootstrap'] }),
+ queryClient.invalidateQueries({ queryKey: ['identities', account.id] }),
+ ])
+ notify('Email addresses saved.')
+ onClose()
+ } catch (e) {
+ setError(friendlyError(e))
+ } finally {
+ setSaving(false)
+ }
+ }}
+ >
+ <div className="alias-list grid">
+ <div className={row}>
+ <span className="alias-email min-w-0 text-[13px] [overflow-wrap:anywhere]">
+ {account?.email}
+ </span>
+ <span className="alias-primary col-span-2 text-[11px] text-muted">Account address</span>
+ </div>
+ {aliases.map((alias, index) => (
+ <div className={row} key={alias.id || alias.email}>
+ <span className="alias-email min-w-0 text-[13px] [overflow-wrap:anywhere]">
+ {alias.email}
+ </span>
+ <input
+ className="alias-name h-8 py-0 px-2.5 text-[12px]"
+ aria-label={'Name for ' + alias.email}
+ value={alias.name || ''}
+ maxLength={100}
+ placeholder={account?.senderName || 'Your name'}
+ disabled={saving}
+ onChange={(e) =>
+ setAliases(
+ aliases.map((a, i) => (i === index ? { ...a, name: e.target.value } : a)),
+ )
+ }
+ />
+ <IconButton
+ label={'Remove ' + alias.email}
+ disabled={saving}
+ onClick={() => setAliases(aliases.filter((_, i) => i !== index))}
+ >
+ <X size={14} />
+ </IconButton>
+ </div>
+ ))}
+ </div>
+ <div className="alias-add flex gap-2 mt-3">
+ <input
+ className="h-8 py-0 px-2.5 text-[12px] aria-invalid:border-danger/70"
+ type="email"
+ aria-label="New email address"
+ aria-invalid={!!addError}
+ autoFocus
+ value={email}
+ maxLength={320}
+ placeholder="[email protected]"
+ disabled={saving}
+ onChange={(e) => {
+ setEmail(e.target.value)
+ setAddError('')
+ }}
+ onKeyDown={(e) => {
+ if (e.key !== 'Enter') return
+ e.preventDefault()
+ add()
+ }}
+ />
+ <Button
+ size="small"
+ className="shrink-0"
+ disabled={saving || !email.trim()}
+ onClick={add}
+ >
+ <Plus size={13} />
+ Add
+ </Button>
+ </div>
+ {addError ? (
+ <div role="alert" className={cn(formError, 'mt-2')}>
+ <AlertCircle size={14} />
+ {addError}
+ </div>
+ ) : (
+ <p className="alias-hint mt-2 mb-0 text-[11px] leading-[1.6] text-muted">
+ Addresses without a name of their own use the account’s.
+ </p>
+ )}
+ {error && (
+ <div role="alert" className={formError}>
+ <AlertCircle size={14} />
+ {error}
+ </div>
+ )}
+ <div className="modal-actions flex justify-end gap-2 mt-6">
+ <Button onClick={onClose} disabled={saving}>
+ Cancel
+ </Button>
+ <Button type="submit" variant="primary" disabled={saving}>
+ {saving && <Spinner size={14} />}
+ {saving ? 'Saving…' : 'Save addresses'}
+ </Button>
+ </div>
+ </form>
+ </Modal>
+ )
+}
diff --git a/apps/desktop/src/renderer/src/Composer.tsx b/apps/desktop/src/renderer/src/Composer.tsx
index 6fac4e1..1a4488d 100644
--- a/apps/desktop/src/renderer/src/Composer.tsx
+++ b/apps/desktop/src/renderer/src/Composer.tsx
@@ -1,6 +1,6 @@
import { cn } from '@inlark/ui'
import { useEffect, useRef, useState } from 'react'
-import { useQuery } from '@tanstack/react-query'
+import { useQueries } from '@tanstack/react-query'
import { useForm } from '@tanstack/react-form'
import { Dialog } from '@base-ui/react/dialog'
import { useEditor, useEditorState, EditorContent } from '@tiptap/react'
@@ -41,6 +41,8 @@ import { linkTarget } from './link-target'
import { SignatureParagraph, hasDraftContent, replaceSignature } from './composer-document'
const validAddress = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
+/** One From choice: an account and one of its sending addresses. */
+const senderKey = (accountId: string, identityId: string) => JSON.stringify([accountId, identityId])
/** The editor's own formatting keys, which follow the platform (⌘ on macOS, Ctrl elsewhere). */
const boldKeys = bindingText(['Mod+B'])
const italicKeys = bindingText(['Mod+I'])
@@ -139,11 +141,41 @@ export function Composer({
persisted = useRef(!!initial.serverId || initial.status !== 'local'),
alive = useRef(true)
const account = accounts.find((a) => a.id === draft.accountId)!
- const identities = useQuery({
- queryKey: ['identities', draft.accountId],
- queryFn: () => api.identities(draft.accountId),
+ const senders = useQueries({
+ queries: accounts.map((a) => ({
+ queryKey: ['identities', a.id],
+ queryFn: () => api.identities(a.id),
+ enabled: a.id === draft.accountId || a.status === 'connected',
+ })),
})
- const identity = identities.data?.find((identity) => identity.id === draft.identityId)
+ const identities = senders[accounts.indexOf(account)]
+ const identity = identities?.data?.find((i) => i.id === draft.identityId)
+ // The address was removed since this draft was written; never swap in another one silently.
+ const senderMissing = !!identities?.data?.length && !identity
+ const fromOptions = accounts.flatMap((a, index) => {
+ const label = (email: string, name?: string) =>
+ [accounts.length > 1 && a.name, name ? name + ' <' + email + '>' : email]
+ .filter(Boolean)
+ .join(' ¡ ')
+ // A draft saved on the server belongs to its account; only its address can change.
+ const disabled = a.id !== draft.accountId && !!draft.serverId
+ const list = senders[index]?.data
+ if (!list?.length) {
+ const identityId = a.id === draft.accountId ? draft.identityId : ''
+ return [{ value: senderKey(a.id, identityId), label: label(a.email), disabled }]
+ }
+ return list.map((i) => ({
+ value: senderKey(a.id, i.id),
+ label: label(i.email, i.name),
+ disabled,
+ }))
+ })
+ if (senderMissing)
+ fromOptions.unshift({
+ value: senderKey(draft.accountId, draft.identityId),
+ label: 'Choose an address to send from',
+ disabled: true,
+ })
const signature = identity ? identitySignature(settings, identity) : undefined
const locked = sending || changingFrom || draft.status === 'uncertain' || draft.status === 'sent'
const lockedRef = useRef(locked)
@@ -320,8 +352,9 @@ export function Composer({
else focusRecipient(field)
return
}
- if (!latest.current.identityId) {
- notify('Select a sending identity.', 'error')
+ if (!latest.current.identityId || senderMissing) {
+ notify('Choose the address to send this message from.', 'error')
+ document.getElementById('compose-from')?.focus()
return
}
setSending(true)
@@ -386,7 +419,7 @@ export function Composer({
text: editor.getText(),
})
}
- const selectAccount = async (accountId: string) => {
+ const selectAccount = async (accountId: string, identityId?: string) => {
if (lockedRef.current || latest.current.serverId || accountId === latest.current.accountId)
return
setChangingFrom(true)
@@ -396,7 +429,7 @@ export function Composer({
// A sync already underway may have bound the draft to its original account.
if (!alive.current || latest.current.serverId) return
if (!identities.length) throw new Error('This account has no permitted sending identities.')
- selectIdentity(identities[0])
+ selectIdentity(identities.find((i) => i.id === identityId) || identities[0])
} catch (error) {
notify(friendlyError(error), 'error')
} finally {
@@ -589,47 +622,18 @@ export function Composer({
<label htmlFor="compose-from">From</label>
<Select
id="compose-from"
- value={draft.accountId}
- disabled={locked || !!draft.serverId}
- options={accounts.map((a) => ({ value: a.id, label: a.name + ' ¡ ' + a.email }))}
- onValueChange={(accountId) => void selectAccount(accountId)}
+ value={senderKey(draft.accountId, draft.identityId)}
+ disabled={locked}
+ options={fromOptions}
+ onValueChange={(value) => {
+ const [accountId, identityId] = JSON.parse(value) as [string, string]
+ if (accountId !== draft.accountId)
+ return void selectAccount(accountId, identityId)
+ const identity = identities?.data?.find((i) => i.id === identityId)
+ if (identity) selectIdentity(identity)
+ }}
/>
</div>
- {(identities.data?.length || 0) > 1 && (
- <div
- className={cn(
- 'compose-field flex items-center min-h-10.5 border-b border-solid border-b-border gap-2.75 [&>label]:w-10.75',
- '[&>label]:shrink-0 [&>label]:text-[11px] [&>label]:text-muted [&>span]:w-10.75 [&>span]:shrink-0',
- '[&>span]:text-[11px] [&>span]:text-muted [&_input]:flex-1 [&_input]:border-0 [&_input]:py-1.75 [&_input]:px-0',
- '[&_input]:bg-none [&_input]:bg-transparent [&_input]:text-[12px] [&_input]:min-w-0 [&>.select-trigger]:flex-1',
- '[&>.select-trigger]:h-8 [&>.select-trigger]:py-0 [&>.select-trigger]:pr-1 [&>.select-trigger]:pl-0',
- '[&>.select-trigger]:border-0 [&>.select-trigger]:bg-none [&>.select-trigger]:bg-transparent',
- '[&>.select-trigger]:text-foreground [&>.select-trigger]:text-[12px] [&>.select-trigger]:whitespace-normal',
- '[&>.select-trigger:hover:not([data-disabled])]:bg-none',
- '[&>.select-trigger:hover:not([data-disabled])]:bg-transparent [&>button]:text-[11px] [&>button]:bg-none',
- '[&>button]:bg-transparent [&>button]:border-0 [&>button]:text-muted [&>button]:whitespace-nowrap',
- '[&_.subject-input]:font-medium [&_input:focus-visible]:outline-none',
- '[&>.select-trigger:focus-visible]:outline-none focus-within:border-b-primary-solid',
- '[&>.compose-cc-toggle]:self-start [&>.compose-cc-toggle]:mt-2.25 [&>.compose-cc-toggle]:py-0',
- '[&>.compose-cc-toggle]:px-[2px] [&>.compose-cc-toggle:hover]:text-foreground',
- )}
- >
- <label htmlFor="compose-identity">Identity</label>
- <Select
- disabled={locked}
- id="compose-identity"
- value={draft.identityId}
- options={(identities.data || []).map((i) => ({
- value: i.id,
- label: i.name + ' <' + i.email + '>',
- }))}
- onValueChange={(identityId) => {
- const identity = identities.data?.find((identity) => identity.id === identityId)
- if (identity) selectIdentity(identity)
- }}
- />
- </div>
- )}
{addressField('to', 'To')}
{showCc && (
<>
@@ -829,7 +833,7 @@ export function Composer({
)}
</Button>
<span className="compose-account flex-1 text-right text-muted text-[11px] max-[700px]:text-[10px]">
- {account.email}
+ {identity?.email ?? (senderMissing ? '' : account.email)}
</span>
<IconButton
label="Discard draft"
diff --git a/apps/desktop/src/renderer/src/Settings.tsx b/apps/desktop/src/renderer/src/Settings.tsx
index eaecc4a..c4f8f09 100644
--- a/apps/desktop/src/renderer/src/Settings.tsx
+++ b/apps/desktop/src/renderer/src/Settings.tsx
@@ -4,6 +4,7 @@ import { Wordmark } from '@inlark/ui/components/wordmark'
import appIcon from '../../../resources/icon.svg?no-inline'
import {
Plus,
+ AtSign,
ChevronDown,
Mail,
RefreshCw,
@@ -32,6 +33,7 @@ import { AccountAvatarPicker } from './AccountAvatarPicker'
import { SignatureSettings } from './SignatureSettings'
import { AccountSetup, type SetupMode } from './AccountSetup'
import { FolderMappingsDialog } from './FolderMappings'
+import { AliasesDialog } from './Aliases'
import { IndexingMeter } from './IndexingMeter'
import { ShortcutEditor } from './ShortcutEditor'
@@ -168,7 +170,8 @@ export function SettingsPanel({
[setup, setSetup] = useState<{ mode: SetupMode; account?: Account } | undefined>(initialSetup),
[remove, setRemove] = useState<Account>(),
[editing, setEditing] = useState<string>(),
- [folders, setFolders] = useState<Account>()
+ [folders, setFolders] = useState<Account>(),
+ [aliases, setAliases] = useState<Account>()
const modalRef = useRef<HTMLDivElement>(null)
/** Leaves setup and puts focus back where the account list starts. */
const closeSetup = () => {
@@ -543,6 +546,12 @@ export function SettingsPanel({
</strong>
<span className="settings-account-email block text-muted text-[12px] leading-[1.6]">
{account.email}
+ {!!account.aliases?.length &&
+ ' ¡ ' +
+ account.aliases.length +
+ (account.aliases.length === 1
+ ? ' more address'
+ : ' more addresses')}
</span>
<small
className={cn(
@@ -610,10 +619,16 @@ export function SettingsPanel({
Edit connection…
</MenuItem>
{protocol === 'imap' && (
- <MenuItem onClick={() => setFolders(account)}>
- <Folder size={14} />
- Folders…
- </MenuItem>
+ <>
+ <MenuItem onClick={() => setAliases(account)}>
+ <AtSign size={14} />
+ Email addresses…
+ </MenuItem>
+ <MenuItem onClick={() => setFolders(account)}>
+ <Folder size={14} />
+ Folders…
+ </MenuItem>
+ </>
)}
<MenuItem
onClick={() =>
@@ -815,6 +830,12 @@ export function SettingsPanel({
</div>
</div>
</Modal>
+ <AliasesDialog
+ key={aliases?.id || 'aliases-closed'}
+ account={aliases}
+ onClose={() => setAliases(undefined)}
+ notify={notify}
+ />
<FolderMappingsDialog
key={folders?.id || 'folders-closed'}
account={folders}
diff --git a/apps/desktop/src/renderer/src/demo.ts b/apps/desktop/src/renderer/src/demo.ts
index 9f18518..938002c 100644
--- a/apps/desktop/src/renderer/src/demo.ts
+++ b/apps/desktop/src/renderer/src/demo.ts
@@ -43,7 +43,11 @@ const palette = ['#a69aef', '#83bba8', '#e7ae7c', '#7caee4', '#d491ac']
*/
const demoStates: Partial<Account>[] = [
{ protocol: 'jmap' },
- { protocol: 'imap', indexing: { indexed: 12_340, total: 50_000, complete: false } },
+ {
+ protocol: 'imap',
+ indexing: { indexed: 12_340, total: 50_000, complete: false },
+ aliases: [{ id: 'studio-hello', email: '[email protected]', name: 'Paul at Studio' }],
+ },
{
protocol: 'imap',
limits: {
@@ -754,6 +758,14 @@ export const demoAPI: DesktopMailAPI = {
listeners.forEach((fn) => fn({ type: 'accounts', accounts }))
return accounts
},
+ setAliases: async (accountId, aliases) => {
+ const account = demoAccounts.find((a) => a.id === accountId)
+ if (!account) throw new Error('Account not found.')
+ account.aliases = aliases.map((alias) => ({ ...alias, id: alias.id || crypto.randomUUID() }))
+ const accounts = demoAccounts.map((a) => ({ ...a }))
+ listeners.forEach((fn) => fn({ type: 'accounts', accounts }))
+ return accounts
+ },
mailboxes: async (accountId) => {
if (!folders.has(accountId))
folders.set(
@@ -783,14 +795,19 @@ export const demoAPI: DesktopMailAPI = {
.get(accountId)!
.map((box) => (box.role === 'inbox' ? { ...box, unreadEmails: unreadCount } : box))
},
- identities: async (id) => [
- {
- id: 'identity',
- accountId: id,
- name: demoAccounts.find((a) => a.id === id)!.senderName || 'Paul',
- email: demoAccounts.find((a) => a.id === id)!.email,
- },
- ],
+ identities: async (id) => {
+ const account = demoAccounts.find((a) => a.id === id)!
+ const name = account.senderName || 'Paul'
+ return [
+ { id: 'identity', accountId: id, name, email: account.email },
+ ...(account.aliases || []).map((alias) => ({
+ id: alias.id,
+ accountId: id,
+ name: alias.name || name,
+ email: alias.email,
+ })),
+ ]
+ },
query: async (query, cursor) => {
const pages = demoAccounts.flatMap((account, accountIndex) => {
if (
diff --git a/packages/core/src/model.ts b/packages/core/src/model.ts
index 7d968aa..bcce221 100644
--- a/packages/core/src/model.ts
+++ b/packages/core/src/model.ts
@@ -36,6 +36,11 @@ export interface Account {
email: string
/** The name recipients see in the From header; falls back to the server identity's name. */
senderName?: string
+ /**
+ * Other addresses this account may send from, such as aliases set up with the provider. Only
+ * IMAP accounts keep them here; JMAP servers list their own identities.
+ */
+ aliases?: Alias[]
color: string
seed?: string
image?: string
@@ -52,6 +57,16 @@ export interface Account {
/** Present while the local index is still catching up with the server. */
indexing?: IndexingProgress
}
+/** An address the provider delivers to this account and lets it send from. */
+export interface Alias {
+ /** Identifies the alias as a sending identity, so drafts and signatures follow it. */
+ id: string
+ email: string
+ /** The name recipients see; falls back to the account's sender name. */
+ name?: string
+}
+/** An alias to save; one without an ID is new. */
+export type AliasInput = Omit<Alias, 'id'> & { id?: string }
export interface AccountLimits {
move?: string
destroy?: string
@@ -289,7 +304,7 @@ export interface JmapConnectionConfig {
}
export interface ImapConnectionConfig {
protocol: 'imap'
- /** The single address this account sends from. */
+ /** The account's own address. Aliases are kept on the account. */
email: string
incoming: ServerSettings
outgoing: ServerSettings
@@ -526,6 +541,8 @@ export interface DesktopMailAPI {
reconnect(connectionId: string): Promise<void>
updateAccount(accountId: string, appearance: AccountAppearance): Promise<Account[]>
updateAccountDetails(accountId: string, details: AccountDetails): Promise<Account[]>
+ /** Replaces an IMAP account's aliases. The provider must already deliver and accept them. */
+ setAliases(accountId: string, aliases: AliasInput[]): Promise<Account[]>
mailboxes(accountId: string): Promise<Mailbox[]>
identities(accountId: string): Promise<Identity[]>
query(query: MailQuery, cursor?: Record<string, number>): Promise<QueryPage>
diff --git a/packages/core/src/schemas.ts b/packages/core/src/schemas.ts
index 6813ac8..677f0eb 100644
--- a/packages/core/src/schemas.ts
+++ b/packages/core/src/schemas.ts
@@ -85,6 +85,19 @@ export const accountDetailsSchema = z.object({
name: z.string().max(100),
senderName: z.string().max(100),
})
+export const aliasesSchema = z
+ .array(
+ z.object({
+ id: z.string().uuid().optional(),
+ email: z.string().trim().pipe(z.email().max(320)),
+ name: z
+ .string()
+ .max(100)
+ .refine((value) => !/[\r\n]/.test(value))
+ .optional(),
+ }),
+ )
+ .max(50)
export const appearanceSchema = z.object({
seed: z.string().min(1).max(64).optional(),
image: z
@@ -200,6 +213,7 @@ export const ipcSchemas = {
reconnect: z.tuple([id]),
updateAccount: z.tuple([id, appearanceSchema]),
updateAccountDetails: z.tuple([id, accountDetailsSchema]),
+ setAliases: z.tuple([id, aliasesSchema]),
mailboxes: z.tuple([id]),
identities: z.tuple([id]),
query: z.tuple([querySchema, z.record(z.string(), z.number().int().nonnegative()).optional()]),
diff --git a/packages/imap/src/provider.ts b/packages/imap/src/provider.ts
index dc6fe32..c503fab 100644
--- a/packages/imap/src/provider.ts
+++ b/packages/imap/src/provider.ts
@@ -943,6 +943,10 @@ export class ImapProvider implements MailProvider {
return body
}
async identities(account: Account): Promise<Identity[]> {
+ return this.senders(account)
+ }
+ /** The account's own address first, then the aliases the user added in Inlark. */
+ private senders(account: Account): Identity[] {
return [
{
id: 'default',
@@ -951,8 +955,25 @@ export class ImapProvider implements MailProvider {
email: this.options.config.email,
mayDelete: false,
},
+ ...(account.aliases || []).map((alias) => ({
+ id: alias.id,
+ accountId: account.id,
+ name: alias.name || account.senderName || '',
+ email: alias.email,
+ mayDelete: true,
+ })),
]
}
+ /** Never falls back to another address: the user chose who the message is from. */
+ private sender(account: Account, identityId: string): Identity {
+ const identity = this.senders(account).find((i) => i.id === identityId)
+ if (!identity)
+ throw new ProviderError(
+ 'identity',
+ 'The address this message is from was removed from the account. Choose another From address.',
+ )
+ return identity
+ }
getStateToken() {
return undefined
}
@@ -1170,8 +1191,9 @@ export class ImapProvider implements MailProvider {
// Drafts and sending
private async compose(account: Account, draft: Draft, messageId: string, keepBcc: boolean) {
+ const sender = this.sender(account, draft.identityId)
return composeMime({
- from: { name: account.senderName || '', email: this.options.config.email },
+ from: { name: sender.name, email: sender.email },
to: draft.to,
cc: draft.cc,
bcc: draft.bcc,
@@ -1193,8 +1215,9 @@ export class ImapProvider implements MailProvider {
keepBcc,
})
}
- private messageId() {
- const domain = this.options.config.email
+ /** On the sender's own domain, so a message from an alias doesn't name the account's. */
+ private messageId(email: string) {
+ const domain = email
.split('@')[1]
?.toLowerCase()
.replace(/[^a-z0-9.-]/g, '')
@@ -1208,7 +1231,7 @@ export class ImapProvider implements MailProvider {
'Choose a Drafts folder in Settings → Accounts → Folders to save drafts on the server.',
)
// Every saved revision gets its own Message-ID so it can be found unambiguously.
- const id = messageId || this.messageId()
+ const id = messageId || this.messageId(this.sender(account, draft.identityId).email)
const mime = await this.compose(account, draft, id, true)
return this.run(async (port) => {
// APPEND flags are checked against the selected folder's permanent flags.
@@ -1240,7 +1263,9 @@ export class ImapProvider implements MailProvider {
const recipients = [...new Set([...draft.to, ...draft.cc, ...draft.bcc].map((a) => a.email))]
// Bcc recipients are only in the envelope, never in the transmitted headers.
const mime = await this.compose(account, draft, messageId, false)
- return { messageId, mime, envelope: { from: this.options.config.email, to: recipients } }
+ // Bounces go to the address the message is from, as recipients would expect.
+ const from = this.sender(account, draft.identityId).email
+ return { messageId, mime, envelope: { from, to: recipients } }
}
async submit(_account: Account, message: OutgoingMessage): Promise<SubmissionOutcome> {
if (!message.mime) throw new ProviderError('submission', 'The message was not prepared.')
diff --git a/packages/imap/src/smtp.ts b/packages/imap/src/smtp.ts
index 2163365..c9d4fcd 100644
--- a/packages/imap/src/smtp.ts
+++ b/packages/imap/src/smtp.ts
@@ -105,7 +105,8 @@ export async function submitSmtp(
},
})
conn.send({ from: envelope.from, to, size: mime.byteLength }, body, (error, info) => {
- if (error || !info) return reject(sendFailure(settings, state, error ?? undefined))
+ if (error || !info)
+ return reject(sendFailure(settings, state, envelope.from, error ?? undefined))
const reasons = new Map(
(info.rejectedErrors ?? []).map((e) => [
(e as SmtpFailure).recipient,
@@ -278,7 +279,12 @@ function connectionLost(
)
}
-function sendFailure(settings: SmtpSettings, state: State, error?: SmtpFailure): ProviderError {
+function sendFailure(
+ settings: SmtpSettings,
+ state: State,
+ from: string,
+ error?: SmtpFailure,
+): ProviderError {
const host = settings.host
const code = error?.responseCode || 0
const said = error?.response ? ` The server said: “${clean(error.response)}”` : ''
@@ -286,7 +292,7 @@ function sendFailure(settings: SmtpSettings, state: State, error?: SmtpFailure):
if (error?.code === 'EENVELOPE') {
const message =
error.command === 'MAIL FROM'
- ? `${host} refused the sender address, so nothing was sent.`
+ ? `${host} refused to send from ${clean(from)}, so nothing was sent. If it's an alias, check that your provider lets this account send from it.`
: error.command === 'RCPT TO'
? `${host} ${temporary ? 'temporarily ' : ''}rejected every recipient, so nothing was sent.`
: error.command === 'DATA'
diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsx
index d55e162..cacc567 100644
--- a/packages/ui/src/components/select.tsx
+++ b/packages/ui/src/components/select.tsx
@@ -2,7 +2,7 @@ import { Select as BaseSelect } from '@base-ui/react/select'
import { cn } from '../lib/utils'
import { Check, ChevronDown } from '../icons'
-export type SelectOption<Value extends string> = { value: Value; label: string }
+export type SelectOption<Value extends string> = { value: Value; label: string; disabled?: boolean }
/** A single-choice picker that opens a menu styled like the app's dropdowns. */
export function Select<Value extends string>({
@@ -68,6 +68,7 @@ export function Select<Value extends string>({
<BaseSelect.Item
key={option.value}
value={option.value}
+ disabled={option.disabled}
className={cn(
'menu-item flex items-center gap-2.25 text-[12px] py-1.75 px-2.5 rounded-xs outline-none cursor-pointer',
'data-highlighted:bg-hover data-highlighted:text-strong data-disabled:opacity-40 [&.danger]:text-danger',
diff --git a/packages/ui/src/icons.tsx b/packages/ui/src/icons.tsx
index 5363429..1957958 100644
--- a/packages/ui/src/icons.tsx
+++ b/packages/ui/src/icons.tsx
@@ -8,6 +8,7 @@ import {
ArrowLeft as ArrowLeftGlyph,
ArrowUp as ArrowUpGlyph,
ArrowUpRight as ArrowUpRightGlyph,
+ AtIcon as AtSignGlyph,
Bold as BoldGlyph,
Calendar as CalendarGlyph,
CalendarAdd02Icon as CalendarAddGlyph,
@@ -93,6 +94,7 @@ export const ArrowDown = icon(ArrowDownGlyph)
export const ArrowLeft = icon(ArrowLeftGlyph)
export const ArrowUp = icon(ArrowUpGlyph)
export const ArrowUpRight = icon(ArrowUpRightGlyph)
+export const AtSign = icon(AtSignGlyph)
export const Bold = icon(BoldGlyph)
export const Calendar = icon(CalendarGlyph)
export const CalendarAdd = icon(CalendarAddGlyph)
diff --git a/tests/imap-provider.test.ts b/tests/imap-provider.test.ts
index b5ff6b2..d52bb89 100644
--- a/tests/imap-provider.test.ts
+++ b/tests/imap-provider.test.ts
@@ -611,6 +611,46 @@ describe('IMAP drafts and sending', () => {
expect(raw).toMatch(/^Message-ID: <[email protected]>/m)
expect(server.commands).not.toContain('APPEND')
})
+ it('sends from an alias in the From header, the envelope and the Message-ID', async () => {
+ const p = await connected()
+ const aliased = {
+ ...account,
+ senderName: 'Me',
+ aliases: [
+ { id: 'hello', email: '[email protected]', name: 'Hello desk' },
+ { id: 'custom', email: '[email protected]' },
+ ],
+ }
+ expect((await p.identities(aliased)).map((i) => [i.id, i.name, i.email, i.mayDelete])).toEqual([
+ ['default', 'Me', '[email protected]', false],
+ ['hello', 'Hello desk', '[email protected]', true],
+ // Without a name of its own, an alias uses the account's.
+ ['custom', 'Me', '[email protected]', true],
+ ])
+ const outgoing = await p.prepareSubmission(
+ aliased,
+ { ...draft, accountId: account.id, identityId: 'hello' },
+ )
+ expect(outgoing.envelope.from).toBe('[email protected]')
+ const raw = new TextDecoder().decode(outgoing.mime)
+ expect(raw).toMatch(/^From: Hello desk <hello@alias\.example>/m)
+ expect(raw).not.toContain('[email protected]')
+ // A saved draft gets a Message-ID on the alias's domain, never the account's.
+ await p.createDraft(aliased, { ...draft, accountId: account.id, identityId: 'custom' })
+ const stored = new TextDecoder().decode(server.box('Drafts').messages[0].raw)
+ expect(stored).toMatch(/^From: Me <me@custom\.example>/m)
+ expect(stored).toMatch(/^Message-ID: <[^@>]+@custom\.example>/m)
+ })
+ it('refuses to send from an address that is no longer set up', async () => {
+ const p = await connected()
+ const removed = { ...draft, accountId: account.id, identityId: 'removed' }
+ await expect(p.prepareSubmission(account, removed, 'attempt@x')).rejects.toMatchObject({
+ code: 'identity',
+ })
+ await expect(p.createDraft(account, removed)).rejects.toMatchObject({ code: 'identity' })
+ expect(server.box('Drafts').messages).toHaveLength(0)
+ })
it('does not duplicate a Sent copy the server already filed', async () => {
const p = await connected()
const outgoing = await p.prepareSubmission(
diff --git a/tests/service-imap.test.ts b/tests/service-imap.test.ts
index d46b8f4..5d9d617 100644
--- a/tests/service-imap.test.ts
+++ b/tests/service-imap.test.ts
@@ -477,3 +477,73 @@ describe('IMAP drafts', () => {
expect(server.box('Drafts').messages[0].input.text?.trim()).toBe('Hello')
})
})
+
+describe('IMAP aliases', () => {
+ beforeEach(() => service.connect(input))
+
+ it('saves aliases, keeps their IDs, and refuses the same address twice', async () => {
+ const [account] = await service.setAliases(accountId, [
+ { email: '[email protected]', name: 'Hello desk' },
+ { email: '[email protected]', name: ' ' },
+ ])
+ expect(account.aliases).toEqual([
+ { id: expect.any(String), email: '[email protected]', name: 'Hello desk' },
+ { id: expect.any(String), email: '[email protected]' },
+ ])
+ const hello = account.aliases![0]
+ // Renaming keeps the ID drafts and signatures refer to; an unknown ID is never adopted.
+ const foreign = '1b3c7e2a-9a4f-4d8e-bb11-0c2d3e4f5a6b'
+ const [renamed] = await service.setAliases(accountId, [
+ { id: hello.id, email: '[email protected]', name: 'Hello' },
+ { id: foreign, email: '[email protected]' },
+ ])
+ expect(renamed.aliases![0]).toEqual({ ...hello, name: 'Hello' })
+ expect(renamed.aliases![1].id).not.toBe(foreign)
+ expect((await service.identities(accountId)).map((i) => [i.name, i.email])).toEqual([
+ ['Hello', '[email protected]'],
+ ])
+ await expect(service.setAliases(accountId, [{ email: '[email protected]' }])).rejects.toThrow(
+ 'already one of this account’s addresses',
+ )
+ await expect(
+ service.setAliases(accountId, [{ email: '[email protected]' }, { email: '[email protected]' }]),
+ ).rejects.toThrow('already one of this account’s addresses')
+ expect(service.accounts[0].aliases).toEqual(renamed.aliases)
+ })
+ it('keeps aliases across a restart and when the connection is edited', async () => {
+ await service.setAliases(accountId, [{ email: '[email protected]' }])
+ const aliases = service.accounts[0].aliases
+ await restart()
+ expect(service.accounts[0].aliases).toEqual(aliases)
+ await service.connect({ ...input, senderName: 'Me' })
+ expect(service.accounts[0].aliases).toEqual(aliases)
+ // An alias that becomes the account's own address is no longer an alias.
+ await service.connect({ ...input, config: { ...input.config, email: '[email protected]' } })
+ expect(service.accounts[0].aliases).toBeUndefined()
+ })
+ it('sends from the chosen alias and files the Sent copy with it', async () => {
+ const [account] = await service.setAliases(accountId, [
+ { email: '[email protected]', name: 'Hello desk' },
+ ])
+ const result = await service.send({ ...draft, identityId: account.aliases![0].id })
+ expect(result).toMatchObject({ status: 'sent', sentCopy: 'filed' })
+ expect(submit.mock.calls[0][1].from).toBe('[email protected]')
+ expect((await journal()).messageId).toMatch(/@alias\.example$/)
+ const sent = new TextDecoder().decode(server.box('Sent').messages[0].raw)
+ expect(sent).toMatch(/^From: Hello desk <hello@alias\.example>/m)
+ })
+ it('refuses to send from a removed alias, and sends nothing', async () => {
+ const [account] = await service.setAliases(accountId, [{ email: '[email protected]' }])
+ const identityId = account.aliases![0].id
+ await service.setAliases(accountId, [])
+ await expect(service.send({ ...draft, identityId })).rejects.toMatchObject({
+ code: 'identity',
+ })
+ expect(submit).not.toHaveBeenCalled()
+ expect((await journal()).state).toBe('rejected')
+ // The draft keeps its address, so the composer asks for a new one instead of guessing.
+ expect((await service.drafts())[0]).toMatchObject({ status: 'error', identityId })
+ })
+})
diff --git a/tests/smtp.test.ts b/tests/smtp.test.ts
index f8ffc50..69b17f2 100644
--- a/tests/smtp.test.ts
+++ b/tests/smtp.test.ts
@@ -239,7 +239,9 @@ describe('SMTP submission', () => {
})
const refused = await failure(submitSmtp(settings(sender.port), envelope(), await message()))
expect(refused.code).toBe('submissionRejected')
- expect(refused.message).toMatch(/sender/)
+ // Names the address, which may be an alias the provider doesn't allow.
+ expect(refused.message).toContain('refused to send from [email protected]')
+ expect(refused.message).toContain('Not your address')
expect(sender.log.rcptTo).toEqual([])
})